__dict__ does not know about some class attributes

If I create a class

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

And then in the console, let's say

x=MyClass()
x.counter = 1
vars(x) # returns {'counter': 1}
x.__dict__ # returns {'counter': 1}

Why doesn't he know about the attribute i x? I am sure this is due to a misunderstanding of my question about how the various class attributes are defined in Python.

Is there any difference between Python 2/3 in this regard? The challenge dir(x)gives me everything I expect.

I suspect that this question was asked by other newcomers, but at this point I do not know the right things to look for in the title of the question. None of the ones suggested by the website seemed correct.

+4
source share
1 answer

i , . , MyClass.i, MyClass:

In [133]: x = MyClass()

In [134]: y = MyClass()

In [135]: x.i, y.i, MyClass.i
Out[135]: (12345, 12345, 12345)

In [136]: MyClass.i = 54321

In [137]: x.i, y.i, MyClass.i
Out[137]: (54321, 54321, 54321)

i, MyClass.__dict__:

In [138]: vars(MyClass)
Out[138]: 
mappingproxy({'__dict__': <attribute '__dict__' of 'MyClass' objects>,
              '__doc__': 'A simple example class',
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
              'f': <function __main__.MyClass.f>,
              'i': 54321})    # <------

, , :

In [148]: class MyClass:
     ...:     i = 12345
     ...:     def __init__(self):
     ...:         self.i = 54321
     ...:         

In [149]: x = MyClass()

In [150]: MyClass.i, x.i
Out[150]: (12345, 54321)
+5

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


All Articles