Python 使用dict作为开关来更新类属性-如何将它们作为引用插入?
嗨,我想节省一些打字时间,通过这样做变得“聪明”Python 使用dict作为开关来更新类属性-如何将它们作为引用插入?,python,dictionary,python-3.x,switch-statement,Python,Dictionary,Python 3.x,Switch Statement,嗨,我想节省一些打字时间,通过这样做变得“聪明” 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, whattoupd
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个这样的属性,因此保存键入并能够将它们添加到列表中非常方便,但我的google fu并没有提供任何令人满意的方法
有任何聪明但仍然可读的建议吗?祝贺你!您刚刚重新创建了一种有限形式的
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']
有什么原因不能只使用名称的
dict
:通过名称进行计数和访问-为什么实例属性需要存在?整数的传递方式与其他方式完全相同。不同之处在于整数是不可变的:i=j=1;断言i是j;i+=1;断言我不是j和i!=j
Hey Jon-这也行得通,我是通过编码进入这个解决方案的,而没有对设计给予足够的关注:-)。我确实喜欢这些属性,因为它们(对我来说)比dict内容更清晰。我决定使用setattr()重新实现。我知道有一个优雅的解决方案,但我没有看到AllowedAttr是如何使用的。。。我认为使用setattr()可能是一种更吸引人的方法。如果您想在这方面提供一些指导,我将非常感激:=)