Python 类。self.key 存在,但 self.__dict__ 中不存在
我的类里面有三个很大的字典,其中一个出现在 self.__dict__
里,另外两个却没有。
举个例子:
class MyClass:
big_matrix = {}
side_array = {}
map_of_data = {}
def __init__( self ):
# etc...
当我试着把 self.__dict__
打印到终端时,我只成功看到了 big_matrix
,其他的字典都没有显示出来。
在 __init__
里没有声明任何数组,它们是在其他函数里后面声明的。
请帮帮我好吗?
2 个回答
2
类属性和实例属性之间的区别最好用一个例子来说明:
In [25]: class MyClass:
....: cls_dict = {} # class attribute
....: def __init__( self ):
....: pass
....:
In [26]:
In [26]: m = MyClass() # first instance
In [27]: m.cls_dict["foo"] = "bar" # first instance adds to dict
In [28]: m1 = MyClass() # second instance
In [29]: m1.cls_dict["bar"] = "foo" # second instance adds to dict
In [30]: MyClass.cls_dict
Out[30]: {'bar': 'foo', 'foo': 'bar'} # both entries in the dict
In [31]: m.cls_dict # can be accessed through the class or an instance
Out[31]: {'bar': 'foo', 'foo': 'bar'}
In [32]: m1.cls_dict
Out[32]: {'bar': 'foo', 'foo': 'bar'}
实例属性:
In [33]: class MyClass:
....: def __init__( self ):
....: self.ins_dict = {}
....:
In [34]: m = MyClass()
In [35]: m.ins_dict["foo"] = "bar"
In [36]: m1 = MyClass()
In [37]: m1.ins_dict["bar"] = "foo"
In [38]: m.ins_dict # each instance has its own `ins_dict`
Out[38]: {'foo': 'bar'}
In [39]: m1.ins_dict
Out[39]: {'bar': 'foo'}
类属性
是所有实例共享的,而实例属性
是为每个实例单独创建的。
每当你改变类属性cls_dict
时,所有实例都会受到影响。
6
你应该在 __init__
这个方法里初始化你的变量,并把它们赋值给对象的 self
,这样这些变量就属于这个实例的命名空间(也就是当你在一个对象上调用 __dict__
时看到的内容)。
如果不这样做,这些变量就不属于你的 对象实例 的命名空间,而是属于 类 的命名空间。
你可能会在实例命名空间里看到 big_matrix
,因为你在类的其他地方创建了 self.big_matrix
。
实例命名空间中的变量
class MyClass:
def __init__( self ):
self.big_matrix = {}
self.side_array = {}
self.map_of_data = {}
这些变量属于实例命名空间:
>>> print MyClass().__dict__
{'big_matrix': {}, 'side_array': {}, 'map_of_data': {}}
类的命名空间里没有任何变量
>>> print MyClass.__dict__
{}
类命名空间中的变量
class MyClass:
big_matrix = {}
side_array = {}
map_of_data = {}
实例的命名空间里没有任何 变量:
>>> print MyClass().__dict__
{}
所有的变量都属于 类 的命名空间(还有其他类使用的变量):
>>> print MyClass.__dict__
{'big_matrix': {}, 'side_array': {}, '__module__': '__main__', 'map_of_data': {}, '__doc__': None}