Define class variable in subclass

Hi all

I’m trying to make a subclass inheriting from a superclass. I have a class variable that should be implemented by the subclass.

My code looks like this:

class mybaseclass:
	def hello(self):
		print(myclassvar)

class mysubclass(mybaseclass):
	myclassvar = 5
	
zzz = mysubclass()
zzz.hello()

Unfortunately, when executing it complains that myclassvar is not defined (see below). But it is defined! It is defined in the subclass. And it will/must be defined in all other subclasses of mybaseclass. How should I do this?

python test.py
Traceback (most recent call last):
File “C:.…\test.py”, line 9, in
zzz.hello()
File “C:.…\test.py”, line 3, in hello
print(myclassvar)
NameError: name ‘myclassvar’ is not defined

It’s an attribute of the class, not instantiated into the function’s namespace. Perhaps you just want:

    print(self.myclassvar)
1 Like

Excellent, that’s it!
Thanks a lot!