简体   繁体   中英

Access overridden class variable in parent of subclass

How to I access a class variable that I expect a subclass to replace?

this is what i want to acchieve:

class Foo():
    var = "Foo"
    @staticmethod
    def print_var():
    print(Foo.var)

class Bar(Foo):
    var = "Bar"

>> Bar.print_var()
>> "Bar

The code above prints "Foo" instead of "Bar"

Don't use staticmethod . At the very least use @classmethod decorator here:

class Foo():
    var = "Foo"

    @classmethod
    def print_var(cls):
        print(cls.var)

class Bar(Foo):
    var = "Bar"

This makes print_var accessible on the class, but is passed a reference to the current class so you can look up var on the 'right' object.

Use staticmethod only if you want to remove all context from a method, turning it into a regular function again.

Demo:

>>> class Foo():
...     var = "Foo"
...     @classmethod
...     def print_var(cls):
...         print(cls.var)
... 
>>> class Bar(Foo):
...     var = "Bar"
... 
>>> Bar.print_var()
Bar
>>> Foo.print_var()
Foo

Use a classmethod :

class Foo():
    @classmethod
    def print_var(cls):
        print(cls.var)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM