2

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"

2
  • Why are you using a static method then? Commented Jul 11, 2014 at 8:50
  • I would like to access it without creating an instance. Is this a bad approach? I'm trying to DRY up some code Commented Jul 11, 2014 at 8:51

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Beat me to it, you've got a wee typo in classmethod
Thank you! The lines between the two have been a bit fuzzy for me.
2

Use a classmethod:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.