避免大量if ... else语句的Python方式?

Nat*_*han 5 python

最近,它已经出现了好几次,我想比以前更好地处理它:我有一系列要在对象和字典之间进行交叉引用的属性。如果它们之间的值不同,我想将object.attribute设置为dictionary ['attribute']值。我还想跟踪正在发生的变化。

现在,我的第一个想法是仅对每个属性使用if else语句,但是在编写了其中一些语句之后,很明显,我一次又一次地重写了相同的代码。必须有一种DRY方法来执行此操作,在该方法中,我仅指定每次更改的部分,然后遍历所有属性。

在生产代码中,有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)
Run Code Online (Sandbox Code Playgroud)

这样的想法是,每当我需要添加另一个属性时,我都可以更新要检查的属性列表,并且其余代码已经编写完毕。用Python的方式可以做到这一点?

Ale*_*amo 5

setattr() 您要寻找的是:

attributeList = (('Name',    'name',    'name'),
                 ('Version', 'version', 'revision'))

for title, obj_attribute, dict_key in attributeList:
    obj_value = getattr(obj, obj_attribute)
    adict_value = adict[dict_key]

    if obj_value == adict_value:
        msg.append('%s is the same' % (obj_value))
    else:
        msg.append('%s was updated from %s to %s' % (title, obj_value, adict_value))

        setattr(obj, obj_attribute, adict_value)
Run Code Online (Sandbox Code Playgroud)