【转】python中的OOP:class attribute 和 instance attribute

参考自:
Instance attribute attribute_name defined outside init

How to avoid having class data shared among instances?

文章目录

explanation

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始终是一样的

但是当进行这样的操作以后,二者的指向就会根据可变/不可变变量进行变化

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值