pythonifelse太多_用Python的方式来避免堆积如山的if…else语句?

这一点最近已经出现过好几次了,我想比以前更好地处理它:我有一系列属性,在对象和字典之间进行交叉引用。如果它们之间的值不同,我想设置对象.属性到字典['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的方法是什么?在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值