29、 super()
- 在类层次结构中调用父类(超类)的方法:
class Parent:
def method(self):
print("Parent method")
class Child(Parent):
def method(self):
super().method()
print("Child method")
child = Child()
child.method()
# 输出:
# Parent method
# Child method
30、 yield from
- 在生成器中委托给另一个生成器或可迭代对象:
def sub_gen():
yield 1
yield 2
def main_gen():
yield from sub_gen()
yield 3
for item in main_gen():
print(item)
# 输出:
# 1
# 2
# 3
31、 __slots__
- 在类定义中限制实例变量,节省内存空间:
class MyClass:
__slots__ = ['attr1', 'attr2'] # 只允许 attr1 和 attr2 作为实例变量
obj = MyClass()
obj.attr1 = 'Value1'
obj.attr2 = 'Value2'
# 下面这行会抛出 AttributeError 异常,因为 'attr3' 不在 __slots__ 中
# obj.attr3 = 'Value3'
32、 @classmethod
和 @staticmethod
- 类装饰器,用于定义类方法和静态方法:
class MyClass:
@classmethod
def class_method(cls):
return cls()
@staticmethod
def static_method():
return "Static method"
# 类方法可以通过类或实例调用,它接收第一个参数为类本身
print(MyClass.class_method() is MyClass())
# 静态方法与普通函数类似,它不依赖于类或实例状态
print(MyClass.static_method())
33、 *args
和 **kwargs
- 在函数定义中接收任意数量的位置参数和关键字参数:
def flexible_function(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
flexible_function(1, 2, 3, key1="value1", key2="value2")
# 输出:
# Positional arguments: (1, 2, 3)
# Keyword arguments: {'key1': 'value1', 'key2': 'value2'}
当前文章价值0.01元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)
评论已关闭!