参考自:
Instance attribute attribute_name defined outside init
How to avoid having class data shared among instances?
class A:
temp='Skyharbor'
def __init__(self, x):
self.x=x
def change(self, y):
self.temp=y
实现一个instance,初始化后赋值会有:
a = A('Tesseract')
>>> print a.temp
Skyharbor
>>> print A.temp
Skyharbor
note that id(a.temp) and id(A.temp) are still the same
未调用change这个方法前这两个attribute是指向同一个内存地址
而Any Python object is automatically given a dict attribute, which contains its list of attributes.
>>> print A.__dict__
{
'change': <function change at 0x7f5e26fee6e0>,
'__module__': '__main__',
'__init__': <function __init__ at 0x7f5e26fee668>,
'temp': 'Monuments',
'__doc__': None
}
>>> print a.__dict__
{x: 'Tesseract'}
Note that temp attribute is listed among A class’s attributes while x is listed for the instance
在这里,虽然temp没有列于instance a的attribute list(dict)中,但得益于python的__getattribute__() 方法,dotted syntax automatically invokes this method。因此,a.temp等价于 a.getattribute(‘temp’)。而这个方法会在不同的地方搜寻这个attribute。
搜寻的顺序如下:
The standard implementation of getattribute() searches first the internal dictionary (dict) of an object, then the type of the object itself. In this case a.getattribute(‘temp’) executes first a.dict[‘temp’] and then a.class.dict[‘temp’]
当调用了change方法后
>>> a.change('Intervals')
>>> print a.temp
Intervals
>>> print A.temp
Monuments
Now if we compare id(a.temp) and id(A.temp), they will be different
二者ID不同了!!!!
原因:因为str是immutable variable,因此当对其进行赋值的时候,会创建一个新的str,a.temp自然指向了新的str,而原来A.temp仍是指向旧的
当instance未对其class instance操作(赋值等)时候,二者的id始终是一样的
但是当进行这样的操作以后,二者的指向就会根据可变/不可变变量进行变化