Skip to main content
 首页 » 编程设计

python 3 : Access a static function from a child class

2024年10月01日7EasonJim

如何从子类访问静态函数。

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 

每个 child 都有自己的一组 bar 列表,我希望他们使用父类中的 foo() 函数打印出正确的字符串。

请您参考如下方法:

class Parent: 
    bar = [] 
    @classmethod 
    def foo(cls): 
        print(' | '.join(cls.bar)) 
 
class Child(Parent): 
    bar = ['baz', 'qux', 'far'] 
Child.foo() 

类方法是绑定(bind)到类而不是其对象的方法。它不需要创建类实例。 Classmethod 将始终返回同一类的实例而不是子类。实际上classmethod会打破OOP的规则。