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?

1
  • If you use function 'dir' like dir(instance), you can see all available methods and functions. Commented Oct 21, 2019 at 9:19

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.