如何改变python字典的__setattr__的行为? [英] How to change the behavior of a python dictionary's __setattr__?

查看:480
本文介绍了如何改变python字典的__setattr__的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,一切都有一个类。因此 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆