Python3:从 child class 访问一个静态函数
Python3: Access a static function from a child class
如何从 child class.
访问静态函数
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
children 每个人都有自己的一组 bar
列表,我希望他们使用 parent class 中的 foo()
函数来打印出正确的字符串。
Class 方法使用 class 名称访问
所以在你的 child class foo 方法是继承的但是你必须用 class name
调用它
class Parent:
bar = []
@classmethod
def foo(cls):
print(' | '.join(cls.bar))
class Child(Parent):
bar = ['baz', 'qux', 'far']
Child.foo() # This will make cls Child class and access child's bar element
### baz | qux | far
class Parent:
bar = []
@classmethod
def foo(cls):
print(' | '.join(cls.bar))
class Child(Parent):
bar = ['baz', 'qux', 'far']
Child.foo()
class 方法是绑定到 class 而不是其对象的方法。它不需要创建 class 实例。 Classmethod 将始终 return 相同 class 的实例,而不是子 class 的实例。实际上class方法会打破OOP的规则。
如何从 child class.
访问静态函数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
children 每个人都有自己的一组 bar
列表,我希望他们使用 parent class 中的 foo()
函数来打印出正确的字符串。
Class 方法使用 class 名称访问
所以在你的 child class foo 方法是继承的但是你必须用 class name
调用它class Parent:
bar = []
@classmethod
def foo(cls):
print(' | '.join(cls.bar))
class Child(Parent):
bar = ['baz', 'qux', 'far']
Child.foo() # This will make cls Child class and access child's bar element
### baz | qux | far
class Parent:
bar = []
@classmethod
def foo(cls):
print(' | '.join(cls.bar))
class Child(Parent):
bar = ['baz', 'qux', 'far']
Child.foo()
class 方法是绑定到 class 而不是其对象的方法。它不需要创建 class 实例。 Classmethod 将始终 return 相同 class 的实例,而不是子 class 的实例。实际上class方法会打破OOP的规则。