これは最近、何度か登場しています。私はこれまでよりもうまく対処したいと思います。オブジェクトと辞書を相互参照する一連の属性があります。値が異なる場合、object.attributeをdictionary ['attribute']値に設定します。私はまた何が変わっているのかを把握したい。if ... else文の山を避けるPythonの方法?
私の最初の考えは、すべての属性に対して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)
この方法は、私は別の属性を追加する必要がある時はいつでも、私は検査されていると、コードの残りの部分が既に書かれている属性のリストを更新することができているという考え。これを達成するためのPythonの方法は何ですか?
これをすべて関数/関数にマージできます。それはあなたのコードをより綺麗に見せ、あなたの人生を楽にします。 – iamandrus
それは私の側で機能している - 私は例を単純化しようとしていた。 – Nathan