检查与指定函数同名的实例变量 class 是否为 None

Check whether class instance variable with same name as specified function is None or not

鉴于以下 class

class Household:
    def __init__(self):
         self.dog=None
         self.cat=None
         self.fish=None
    #setter methods
    ...

和以下函数 在单独的 class 中:

def dog(...):
    ...
def cat(...):
    ...
def fish(...):
    ...

#animal_function is a function, which can either be dog, cat, or fish
def function(homes, animal_function):
    for home in pets:
        #animal_function.__name__ will evaluate to dog, cat, or fish
        #But Python thinks I'm trying to access home.animal_function, which doesn't exist
        if home.animal_function.__name__ is not None:
            ...
            #Setter method
            home.animal_function.__name__=value

给定特定家庭,每个函数(狗、猫和鱼)只能得出一个值。所以我想通过首先检查与参数函数同名的 Household 实例变量是否为 None 来避免重复工作。

如何解决我在评论中列出的问题?谢谢!

使用getattr()动态获取对象的属性(即事先不知道属性的名称):

...
if getattr(home, animal_function.__name__) is not None:
    ...

如果animal_function.__name__ == 'cat',则getattr(home, animal_function.__name__)等同于home.cat