最近出现了好几次,我想比它更好地处理它:我有一系列属性可以在对象和字典之间交叉引用。如果它们之间的值不同,我想将object.attribute设置为dictionary ['attribute']的值。我也想跟踪发生了什么变化。Pythonic的方式,以避免山如果...其他语句?
现在,我的第一个想法是只对每个属性使用if else语句,但在编写其中的一些内容后,很明显我会重复编写相同的代码。必须有一种干式的方法来做到这一点,在那里我只指定每次都在变化的部分,然后遍历所有的属性。
在生产代码中,有15个不同的属性,但下面的示例将简单地使用2。我有一些关于如何以聪明的方式做到这一点的想法,但我错过了实际设置object.attribute等于dictionary ['attribute']值的最后一步。
# Simulated data setup - not under my control IRL
class someClass:
def __init__(self, name, version):
self.name = name
self.version = version
objA = someClass('Test1','1.1')
dictA = {'name':'Test1','revision':'1.2'}
# My code below
# option 1 - a series of for loops
def updateAttributesSimple(obj, adict, msg):
if obj.name == adict['name']:
msg.append('Name is the same')
else:
msg.append('Name was updated from %s to %s' % (obj.name, adict['name']))
obj.name = adict['name']
if obj.version == adict['revision']:
msg.append('Version is the same')
else:
msg.append('Version was updated from %s to %s' % (obj.version, adict['revision']))
obj.version = adict['revision']
# option 2 - trying to be clever about this
def updateAttributesClever(obj, adict, msg):
attributeList = (('Name', obj.name, adict['name']),
('Version', obj.version, adict['revision']))
for valTuple in attributeList:
if valTuple[1] == valTuple[2]:
msg.append('%s is the same' % (valTuple[0]))
else:
msg.append('%s was updated from %s to %s' % (valTuple[0], valTuple[1], valTuple[2]))
# code to set valTuple[1] = valTuple[2] goes here, but what is it?
# valTuple[1] = valTuple[2] attempts to set the desired value to a string, rather than the attribute of obj itself
msg = ['Updating Attributes simple way:']
updateAttributesSimple(objA, dictA, msg)
print '\n\t'.join(msg)
#reset data
objA = someClass('Test1','1.1')
dictA = {'name':'Test1','revision':'1.2'}
msg = ['Updating Attributes clever way:']
updateAttributesClever(objB, dictB, msg)
print '\n\t'.join(msg)
的想法是这样,每当我需要添加另一个属性,我可以更新被检查的属性列表和其余代码已经编写完成。 Pythonic的方法是什么?
您可以将所有这些合并到一个函数中。它会让你的代码看起来更整洁,让你的生活更轻松。 – iamandrus 2011-04-12 19:46:51
它在我身边的功能 - 我只是试图简化这个例子。 – Nathan 2011-04-12 21:27:59