如何在我的Python代码中用同一个主体进行多次检查以避免违反DRY?
例如,我需要在我的Django项目中进行检查。
if not obj.name == instance.name:
post_response('CHANGED')
if not obj.address == instance.address:
post_response('CHANGED')
if not obj.phone_number == instance.phone_number:
post_response('CHANGED')
if not obj.postal_code == instance.postal_code:
post_response('CHANGED')
我还有多个条件要做。只是感觉是多余的,因为每个条件操作中的body都是一样的。
解决方案:
由于你在两个对象上检查的是同一个属性,你可以像这样动态地比较它们。
attributes = ['name', 'address', 'phone_number', 'postal_code']
for attribute in attributes:
if not getattr(obj, attribute) == getattr(instance, attribute):
post_response('CHANGED')
break
本文来自投稿,不代表实战宝典立场,如若转载,请注明出处:https://www.shizhanbaodian.com/13085.html