Python class instance __dict__ doesn't contain all instance variables. Why?

后端 未结 3 1116
庸人自扰
庸人自扰 2021-01-14 13:37

Here\'s a bit of a newbie Python question about instance variables.

Consider the following Python 2.7 class definition:

class Foo(object):
    a = 1
         


        
相关标签:
3条回答
  • 2021-01-14 13:51

    a is not an instance attribute, it's a class attribute.

    0 讨论(0)
  • 2021-01-14 14:09

    May this help you further?

    >>> class X(object):
    
        def __getattribute__(self, name):
            print name
            return object.__getattribute__(self, name)
    
    
    >>> l = dir(X())
    __dict__
    __members__
    __methods__
    __class__
    >>> l
    ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
    
    0 讨论(0)
  • 2021-01-14 14:12

    Your a isn't an instance variable. You defined it as part of the class.

    >>> class Foo(object):
    ...    a = 1
    ...
    >>> Foo.a
    1
    

    If you want an instance variable you should put it inside the __init__ method, because this method is called when your object is created.

    0 讨论(0)
提交回复
热议问题