使用dict作为开关来更新类属性-如何将它们作为引用插入



嗨,我试图通过这样做来节省一些打字并变得"聪明"。。。

class foo(object):
def __init__()
self.eric = 0
self.john = 0
self.michael = 0
self.switchdict = {'Eric':self.eric, 'John':self.john, 'Michael':self.michael}
def update(self, whattoupdate, value):
if whattoupdate in self.switchdict:
self.switchdict[whattoupdate] += value

在它不起作用之后,很明显,整数值不是通过引用传递的,而是作为整数传递的。我花了很长时间把属性变成列表,但我怀疑还有更好的方法。

事实上,我有大约30个这样的属性,所以保存输入并将它们添加到列表中是非常方便的,但我的谷歌功能并没有产生任何令人满意的方法。

有什么聪明但仍然可读的Python建议吗?

祝贺您!您刚刚重新设计了setattr()的有限形式。:-)

如果你在这条路上走得很远,我认为你会陷入维护噩梦,但如果你坚持,我会考虑这样的事情:

class foo(object):
allowedattrs = ['eric', 'john', 'michael']
def __init__(self):
self.eric = 0
self.john = 0
self.michael = 0
self.switchdict = {'Eric':self.eric, 'John':self.john, 'Michael':self.michael}
def update(self, whattoupdate, value):
key = whattoupdate.lower()
if key not in self.allowedattrs:
raise AttributeError(whattoupdate)
setattr(self, key, getattr(self, key) + value)
f = foo()
f.update('john', 5)
f.update('john', 4)
print f.john

但是,把你的价值观存储在一个好的defaultdict中真的会容易得多吗?

from collections import defaultdict
class foo(object):
allowedattrs = ['eric', 'john', 'michael']
def __init__(self):
self.values = defaultdict(int)
def update(self, whattoupdate, value):
self.values[whattoupdate] += value
f = foo()
f.update('john', 5)
f.update('john', 4)
print f.values['john']

最新更新