如何改变python字典的__setattr__的行为? [英] How to change the behavior of a python dictionary's __setattr__?
问题描述
dict
也有一个类。 所以理论上,我应该可以改变keyvalue赋值行为的实现。
< br>
示例:
d = dict()
d ['first'] = 3#内部d ['first']存储为6 [ie值* 2如果值为INT]
打印d ['first']#应打印6
d ['second'] = 4
print d ['second']#should print 8
我注意到大多数对象具有列于 OBJECT .__ dict __
或 vars(OBJECT)
中的属性。但是,对于 dict
或列表
,则不是这样。
如何通过覆盖 dict .__ setattr __()
方法获得所需的行为?
这是 __ setitem __
在这种情况下必须被覆盖 -
和它就像:
class MyDict(dict):
def __setitem __(self,key,value):
dict .__ setitem __(self,key,2 * value)
示例:
>>> m = MyDict()
>>> m [0] = 5
>>>> m
{0:10}
__ setattr __
控制对象属性本身(不是键/值对)的属性。
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.
这篇关于如何改变python字典的__setattr__的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!