Search code examples
pythonfunctioninstance-variables

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


Given the following class

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

and the following functions in a separate 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

Each function (dog, cat, and fish) can only result in a single value given a specific household. So I want to avoid repeated work by first checking if the Household's instance variable with the same name as the parameter function is None or not.

How can I get around the problem I outlined in the comment? Thanks!


Solution

  • Use getattr() to get attributes of an object dynamically (i.e. without knowing the name of the attribute in advance):

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

    If animal_function.__name__ == 'cat', for example, then getattr(home, animal_function.__name__) is equivalent to home.cat.