这一点最近已经出现过好几次了,我想比以前更好地处理它:我有一系列属性,在对象和字典之间进行交叉引用。如果它们之间的值不同,我想设置对象.属性到字典['attribute']值。我还想知道发生了什么变化。在
现在,我的第一个想法是对每个属性都使用if-else语句,但是在写了一些这样的语句之后,很明显我在一遍又一遍地编写相同的代码。必须有一种干巴巴的方法来完成这项工作,我只指定每次更改的部分,然后循环遍历所有属性。在
在生产代码中,有15个不同的属性,但为了简单起见,下面的示例只使用2个。我对如何用一种聪明的方式来做这件事有一些想法,但是我错过了实际设置对象.属性等于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)
这样,每当我需要添加另一个属性时,我就可以更新正在检查的属性列表,剩下的代码就已经编写好了。Python的方法是什么?在