python setattri_如何改变python字典的__setattr__的行为?

在Python中,一切皆对象,字典也不例外。可以通过覆盖`__setitem__`方法来改变字典键值对的默认赋值行为。例如创建一个MyDict类,重写`__setitem__`方法,使得键对应的值在存储时变为原来的两倍。这样,当向字典中添加元素时,值会自动翻倍。这种自定义行为让字典具备了特定的功能性。
摘要由CSDN通过智能技术生成

In Python, everything has a class. Therefore dict also has a class.

So, in theory, I should be able to change the implementation of the keyvalue assignment behavior.

Example:

d = dict()

d['first'] = 3 # Internally d['first'] is stored as 6 [i.e. value*2 if value is INT]

print d['first'] # should print 6

d['second'] = 4

print d['second'] # should print 8

I noticed that most objects have attributes listed in OBJECT.__dict__ or vars(OBJECT). But this isn’t the case for dict or list.

How can I get the desired behavior by overriding dict.__setattr__() method?

解决方案

It is __setitem__ that have to be overriden in this case -

and it is as simples as:

class MyDict(dict):

def __setitem__(self, key, value):

dict.__setitem__(self, key, 2 * value)

Example:

>>> m = MyDict()

>>> m[0] = 5

>>> m

{0: 10}

__setattr__ controls how object attributes themselves (not key/value pairs) are attributed.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值