2017-02-03 137 views
0

我該如何做到這一點?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() 
+4

你想要一個_classmethod_一個classmethod,不_staticmethod_。靜態方法的定義是無狀態的。 –

回答

2

您可以使用該

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" 
0

正如在評論中提到的,你需要的是一個類方法。

class Parent: 
    Foo = 'Parent food' 

    @classmethod 
    def bar(cls): 
     print(cls.Foo)