Python从父静态方法调用子静态变量

时间:2017-02-03 09:01:00

标签: python

我基本上如何做到这一点?

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() 

2 个答案:

答案 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)