希望有人能用伪代码帮助我。我无法在这里复制代码,因为它不完全是我自己的。
我有一个如下所示的函数:
for result in results_set:
if conditionA:
# When conditionA is true, test on this_attribute.
if result.this_attribute == "interesting string":
# do things.
if result.this_attribute == "another interesting string"
# do different things.
else:
# ConditionA is false? Test on that_other_attribute instead.
if result.that_other_attribute == "interesting string"
# do the same exact things as above for "interesting string"
if result.that_other_attribute == "another interesting string"
# do the same exact things as above for "another interesting string"
将条件 A 或条件 B 的测试放在 for 循环内似乎非常低效,因为我处理的结果集可能有数千行长。另外,代码看起来很糟糕,因为我只是在重复自己。
感觉我应该能够在循环发生之前测试条件 A/B,并根据该测试告诉 Python 接下来要比较“结果”的哪个属性。
我测试哪个属性将始终取决于 ConditionA 的值。在不久的将来,我也可能会得到条件 B、C 或 D,这将需要检查结果的第三个、第四个或第五个属性。
目前,我通过使用两个几乎相同的函数来解决这个问题,每个函数都有自己的“for”,但内部没有 ConditionA 测试...但这看起来很糟糕,当 B、C 或 D 滚动时,这将成为一场噩梦。
是否可以以某种方式拥有属性占位符?如果可以,请问如何?
<小时/>编辑:
我正在努力实现这样的目标......
result = a filler value used only to reference attribute names
if ConditionA:
check_attribute = result.this_attribute
else:
check_attribute = result.that_other_attribute
for result in results_set:
if check_attribute == "interesting string":
# do things.
if check_attribute == "another interesting string"
# do different things.
最佳答案
使用 getattrs 可能会让您到达这里,尽管听起来不太可能。在 for 循环的正上方,你可以这样做
value_to_check = "this_attribute" if conditionA else "that_other_attribute".
是的,那些是字符串。
接下来,在 for
循环中,您可以执行以下操作
result_value = getattr (result, value_to_check)
if result_value == "interesting string": #thing to do
elif result_value == "another interesting string": #other thing to do
关于python - 有没有办法实现Python对象属性的占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48979605/