有没有办法为Python对象属性实现一种占位符?

2024-10-01 15:30:45 发布

您现在位置:Python中文网/ 问答频道 /正文

希望有人能帮我做些伪代码。我不能复制这里的代码,因为它不完全是我自己的。你知道吗

我有一个函数如下所示:

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"

将conditionA或conditionB的测试放在for循环中似乎非常低效,因为我处理的结果集可能有几千行长。加上代码看起来很糟糕,因为我只是在重复我自己。你知道吗

感觉我应该能够在循环发生之前测试conditionA/B,并告诉Python基于该测试下一步比较“result”的哪个属性。你知道吗

我测试哪个属性总是取决于ConditionA的值。在不久的将来,我可能会得到一个条件b、C或D,这将需要检查result的第三、第四或第五个属性。你知道吗

目前我通过两个几乎相同的函数来解决这个问题,每个函数都有自己的“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.

Tags: forstringif属性thatanotherattributeresult
1条回答
网友
1楼 · 发布于 2024-10-01 15:30:45

使用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

相关问题 更多 >

    热门问题