- 子类调用基类未重写的类方法:
- 子类会调用基类中定义的类方法。因为类方法属于类本身,当子类没有重写该类方法时,会沿着继承链向上查找并调用基类的类方法。
- 代码示例:
class BaseClass:
@classmethod
def class_method(cls):
print("This is the base class method.")
class SubClass(BaseClass):
pass
SubClass.class_method()
- 解释:在上述代码中,
SubClass
继承自 BaseClass
且没有重写 class_method
。当 SubClass.class_method()
被调用时,由于 SubClass
自身没有定义 class_method
,它会向上查找并调用 BaseClass
中的 class_method
,所以输出 This is the base class method.
。
- 子类重写类方法后调用:
- 子类会调用自身重写的类方法。这是因为在查找类方法时,首先会在子类中查找,如果找到了则直接调用子类的方法,不会再向上查找基类的方法。
- 代码示例:
class BaseClass:
@classmethod
def class_method(cls):
print("This is the base class method.")
class SubClass(BaseClass):
@classmethod
def class_method(cls):
print("This is the subclass overridden method.")
SubClass.class_method()
- 解释:在这段代码中,
SubClass
重写了 BaseClass
的 class_method
。当 SubClass.class_method()
被调用时,由于 SubClass
自身定义了 class_method
,所以会调用子类重写后的方法,输出 This is the subclass overridden method.
。