我基本上如何做到这一点?
class Parent:
Foo = 'Parent food'
@staticmethod
def bar():
# want to print whatever the child's Foo is
class Child(Parent):
Foo = 'Child foo'
# This should print "Child foo"
Child.bar()
答案 0 :(得分:3)
您可以使用classmethod
作为
class Parent:
Foo = 'Parent food'
@classmethod
def bar(cls):
print cls.Foo
class Child(Parent):
Foo = 'Child foo'
Child.bar()
# This will print "Child foo"
答案 1 :(得分:0)
正如评论中所提到的,你需要的是一种类方法。
class Parent:
Foo = 'Parent food'
@classmethod
def bar(cls):
print(cls.Foo)