Can I access class variables using self?

I have a Foo class with a remote class variable. Can I access a variable of the remote class using self.remote ?

 class Foo: remote = False def __init__(self): self.remote = True @classmethod def print_remote(cls): print(cls.remote) #prints False but why? 
+5
source share
3 answers

Assigning remote to self in __init__ means that instance.remote detected first when you access it through self (in the absence of descriptors). To get both options, use either self or type(self) , that is, either from an instance or from a class:

 def print_remote(self): print(type(self).remote) # class remote print(self.remote) # instance remote 

type(self).remote is essentially equivalent to self.__class__.remote , but in general, you should avoid capturing dunder names ( __*__ ) when there is a built-in that does this for you ( type in this case) sub>

They live in different dictionaries and are different variables. self.remote lives in the dict instance, and class.remote in the dict class.

 >>> Foo().__dict__['remote'] True >>> Foo.__dict__['remote'] False 

When you access through cls using classmethod (or type(self) in a regular method), you will get the first class, when you access through self , you will get an instance.

+7
source
 In [1]: class Foo: ...: x = 0 ...: In [2]: f = Foo() In [4]: f.__dict__ # empty Out[4]: {} In [5]: Foo.__dict__ # have the variable x = 0 Out[5]: mappingproxy({'__dict__': <attribute '__dict__' of 'Foo' objects>, '__doc__': None, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Foo' objects>, 'x': 0}) 

When you try to access a variable in an object, Python will first look in the object, if it does not exist, then it looks in the dict class.

 In [6]: Foo.x = 10 # changing class variable In [7]: f.__dict__ # still empty. Out[7]: {} In [8]: fx # gives you Foo x as object doesn't have that item. Out[8]: 10 In [9]: fx = 20 # this line creates a new variable in x. Now both class and object has their own variable x In [10]: f.__dict__ # f has its own x. Out[10]: {'x': 20} In [11]: Foo.__dict__ # Foo has its own x. Out[11]: mappingproxy({'__dict__': <attribute '__dict__' of 'Foo' objects>, ... 'x': 10}) In [12]: fx # always you will get the value from f.__dict__ Out[12]: 20 In [16]: fx = 50 # changing the value of object variable In [17]: Foo.x # above statement didn't affect class variable. Out[17]: 10 In [13]: del fx # delete object x In [14]: fx # now f doesn't have x, you get the value from class Foo. Out[14]: 10 
+3
source

Yes, you can access the class variable with self. But, if you have an instance variable, you will access the instance variable when using self, as it obscures the class variable.

+1
source

Source: https://habr.com/ru/post/1268711/


All Articles