0

I wonder if we can call variable initiated in self in class method. For example:

class ABC():
    def method1(self):
        self.var1 = '123'

    @classmethod
    def callvar1(cls):
        '''print var1'''

I want to achieve the same output like this:

class ABC():

    var1 = '123'
    
    def method1(self):
        self.var1 = '123'

    @classmethod
    def callvar1(cls):
        print(cls.var1)

How can I access self.var1 in callvar1?

1
  • No, there is no instance state in a classmethod, that's the whole point. You could pass the instance explicitly as another argument... seems inelegant though Commented Jun 24, 2020 at 3:23

3 Answers 3

1

Since callvar1 is a class method, it does not have access to self. This is because the method is not tied to a specific instance of the class, but rather to the class itself. Therefore, when you call the method, it does not know which instance you are referring to. As you did in the second block of the code, you must pass the object whose var1 you would like to print to the function.

Your other option would be to not make it a class method.

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

Comments

1

Class methods are bound to the class itself rather than a particular instance of it so if you're trying to access self.var1 (an instance variable) inside the class method you're not going to have much fun.

Your best option is to simply make the method not a class method (depending on your use case):

>>> class ABC():
...     var1 = '123'
...     def method1(self):
...         self.var1 = '123'
...     def callvar1(self):
...         print(self.var1)
...
>>> b = ABC()
>>> b.callvar1()
123

Although another option is to pass an instance of the class to the class method:

>>> class ABC():
...     var1 = '123'
...     def method1(self):
...         self.var1 = '123'
...     @classmethod
...     def callvar1(cls, inst):
...         print(inst.var1)
...
>>> b = ABC()
>>> ABC.callvar1(b)
123

Comments

0

Use the self keyword to access members of the class.

class ABC():

    var1 = '123'
    
    def method1(self):
        self.var1 = '123'

    @classmethod
    def callvar1(self):
        print(self.var1)

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.