Use a class variable across inheritance in Python
Question:
In Python, I want to define a top level class that can depend on a class variable. Then I want to be able to change that variable at the class level, for children of the class, but still inherit the functionality that uses that variable.
In general, my Parent class has some functions that depend on configuration variables. All my child classes use those same functions, but with different parameters. I would like to be able to change the parameters at the class level.
As the simplest example, here are two classes where the Parent
defines functions in terms of my_global
, then the Child
attempts to change that variable (but fails)
class Parent():
my_global = "parent"
def _init_(self):
pass
def printmg(self):
print(Parent.my_global)
class Child(Parent):
my_global = "child"
my_parent = Parent()
my_parent.printmg()
my_child = Child()
my_child.printmg()
This outputs
parent
parent
While I would like it to output
parent
child
I don’t wan’t to keep the variables at the object level (i.e. self.my_global = "child"
), or to rewrite the function for the child.
Answers:
If you don’t need an instance method define printmg
as classmethod
:
@classmethod
def printmg(cls):
print(cls.my_global)
Change the line print(Parent.my_global)
to print(self.my_global)
.
The self operater represents the current class. So printing like this will work.
In Python, I want to define a top level class that can depend on a class variable. Then I want to be able to change that variable at the class level, for children of the class, but still inherit the functionality that uses that variable.
In general, my Parent class has some functions that depend on configuration variables. All my child classes use those same functions, but with different parameters. I would like to be able to change the parameters at the class level.
As the simplest example, here are two classes where the Parent
defines functions in terms of my_global
, then the Child
attempts to change that variable (but fails)
class Parent():
my_global = "parent"
def _init_(self):
pass
def printmg(self):
print(Parent.my_global)
class Child(Parent):
my_global = "child"
my_parent = Parent()
my_parent.printmg()
my_child = Child()
my_child.printmg()
This outputs
parent
parent
While I would like it to output
parent
child
I don’t wan’t to keep the variables at the object level (i.e. self.my_global = "child"
), or to rewrite the function for the child.
If you don’t need an instance method define printmg
as classmethod
:
@classmethod
def printmg(cls):
print(cls.my_global)
Change the line print(Parent.my_global)
to print(self.my_global)
.
The self operater represents the current class. So printing like this will work.