如何从子类访问静态函数。你知道吗
class Parent:
bar = []
@classmethod
def foo(cls):
print(' | '.join(cls.bar))
class Child_A(Parent):
bar = ['abs', 'arq', 'agf']
foo() # ERROR: NameError: name 'foo' is not defined
### abs | arq | agf
class Child_B(Parent):
bar = ['baz', 'bux', 'bet']
foo() # ERROR: NameError: name 'foo' is not defined
### baz | bux | bet
class Child_C(Parent):
bar = ['cat', 'cqy', 'cos']
foo() # ERROR: NameError: name 'foo' is not defined
### cat | cqy | cos
每个子类都有自己的一组bar
列表,我希望它们使用父类中的foo()
函数打印出正确的字符串。你知道吗
类方法是绑定到类而不是对象的方法。它不需要创建类实例。Classmethod将始终返回同一类的实例,而不是子类。实际上classmethod会打破OOP的规则
使用类名访问类方法
因此,在子类中foo方法是继承的,但必须用类名调用它
相关问题 更多 >
编程相关推荐