Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How have access to both cls and self in a method

Tags:

python

I want to have code that does something like this

class myClass():

    def __init__(self):
        self.__var1 = 'var1'

    var2 = 'var2'

    def myNormalMethod(self):
        print self.__var1

    @classmethod
    def myClassMethod(cls):
       print cls.__var2

    #How do I do this?
    def myMethod():
        print self.__var1
        print cls.__var2

Right now the final method does not work as I do not know how I can have access to both self and cls. How do I implement this?

like image 985
user2802557 Avatar asked Jan 24 '17 15:01

user2802557


1 Answers

As a very brief review, self refers to a current instance of the class while cls variables are attached to the class itelf i.e., shared among every instance. Here are some references to help with this, and how I got to your solution:

  • https://stackoverflow.com/a/25577642/5557662
  • Python datamodel docs

I modified your sample code to illustrate the difference and included a solution:

class MyClass:
    __var2 = 'var2'
    var3 = 'var3'

    def __init__(self):
        self.__var1 = 'var1'

    def normal_method(self):
        print self.__var1

    @classmethod
    def class_method(cls):
       print cls.__var2

    def my_method(self):
        print self.__var1
        print self.__var2
        print self.__class__.__var2


if __name__ == '__main__':
    print MyClass.__dict__['var3']

    clzz = MyClass()
    clzz.my_method()

__var2 and var3 are variables saved to the class. You can access any class variable without an instance via __dict__ which represents the name space.

Since class variables become a part of every instance, you can just call self to access them. Alternatively, you can explicitly call self.__class__.__var2 to make it clear where the intended variable is actually stored.

like image 79
KarmaQueenn Avatar answered Sep 30 '22 22:09

KarmaQueenn