Pythonic方法避免了一堆if … else语句?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Pythonic方法避免了一堆if … else语句?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2632字,纯文字阅读大概需要4分钟。
内容图文
![Pythonic方法避免了一堆if … else语句?](/upload/InfoBanner/zyjiaocheng/801/6c24de57e2124808912725793a477dd4.jpg)
最近出现了好几次,我想比以前更好地处理它:我有一系列属性,我在对象和字典之间交叉引用.如果它们之间的值不同,我想将object.attribute设置为dictionary [‘attribute’]值.我还想跟踪变化的内容.
现在,我的第一个想法是只为每个属性使用if else语句,但在写完其中一些之后,很明显我会一次又一次地重写相同的代码.必须有一种DRY方式来执行此操作,其中我仅指定每次更改的部分,然后循环遍历所有属性.
在生产代码中,有15个不同的属性,但下面的示例仅使用2来简化.我对如何以巧妙的方式做到这一点有所了解,但我错过了实际设置object.attribute等于字典[‘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完成此任务的方法?
解决方法:
你正在寻找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)
内容总结
以上是互联网集市为您收集整理的Pythonic方法避免了一堆if … else语句?全部内容,希望文章能够帮你解决Pythonic方法避免了一堆if … else语句?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。