Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python call child static variable from parent static method

Tags:

python

How do I basically do this?

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() 
like image 914
Kousha Avatar asked Oct 30 '25 18:10

Kousha


2 Answers

You can use a classmethod for that

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"
like image 87
saloua Avatar answered Nov 01 '25 08:11

saloua


As mentioned in the comments, what you need is a classmethod.

class Parent:
    Foo = 'Parent food'

    @classmethod
    def bar(cls):
        print(cls.Foo)
like image 22
Daniel Roseman Avatar answered Nov 01 '25 09:11

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!