4

Is there a way to call a class variable from within a method, without using the class name?

So instead of:

class ClassTest:
    var1 = 5
    def __init__(self, var2):
        self.var2 = var2 
        print(ClassTest.var1*self.var2)

How could I call the class name avoiding having to specify the class name ClassTest?

Georgy
  • 12,464
  • 7
  • 65
  • 73
yatu
  • 86,083
  • 12
  • 84
  • 139

1 Answers1

8

You can use self.__class__ or type(self) to refer the class object from instance.

Edit:

The other answers mentioned to use self.var1 to access class-level name var1, but this would get the instance's attribute var1 if the instance has one. So you'll need to make sure the instance does not have such an attribute.

In any way, it is safer to use self.__class__.var1 or type(self).var1, and also gives an indication to the next reader that the attribute is a class attribute.

heemayl
  • 39,294
  • 7
  • 70
  • 76