I am creating a couple of 'Child' classes which are quite similar and thus wanted to group common methods in a parent class. My problem comes when trying to access static variables of the child classes from the super class.
The following code throws the error: NameError: name 'var' is not defined
class Parent:
@staticmethod
def do_something_with_var():
print(var)
class Child(Parent):
var = "Hello world"
Child.do_something_with_var()
Next thing I tried was obviously to declare var in Parent, but the same error persists.
class Parent:
var = ""
@staticmethod
def do_something_with_var():
print(var)
class Child(Parent):
var = "Hello world"
Child.do_something_with_var()
A solution that I found was to receive the sender class, but then the call becomes a bit ugly:
class Parent:
@staticmethod
def do_something_with_var(cls):
print(cls.var)
class Child(Parent):
var = "Hello world"
Child.do_something_with_var(Child)