Member Variables : Use?


class Animal():
    """ I have here , chosen member variable is_hungry."""
    is_hungry = True
    def __init__(self, name, age): = name
        self.age = age

""" Here , creating an instance hippo."""
hippo = Animal("Gary", 5)

print( hippo.is_hungry) # prints True
# and now I'll change hippo.is_hungry = False 

hippo.is_hungry = False

print(hippo.is_hungry) # prints False

#And here if , I print Animal.is_hungry , I get True


Would'nt it be just better to have def init(self, name, age, is_hungry=True) and then change it for each instance separately, if required rather than generating an member variable. Since, Animal.is_hungry will always show True even if we have had many test cases before
I am not able to understand the use of the member/class variable.


well, if all your Animals are hungry, its a bit rubbish to make it an instance variable, this way, you would have to give a value of True for all instances you create


Sorry, I mistakenly posted the article half complete.


If all animals are hungry, its better to use a member/class variable


But, if we use the following init method,it would work too, and print Animal.is_hungry will always print True , which is confusing, since we have changed hippo.is_hungry = False.

class Animal():
    def __init__(self, name, age, is_hungry = True): = name
        self.age = age
        self.is_hungry = is_hungry

"""In the case of class variable is_hungry = True. print Animal.is_hungry always prints True, and even if I change Animal.is_hungry = False, it doesn't affect hippo.is_hungry


yes, it would work. And there is the tricky bit. There are multiply ways to solve a problem, the question is, which is the best one? In the exercise, the focus is more on coding then such programming problems

true, if you change Animal.is_hungry = False only instances create after this change will be affected by this change.


Thanks , alot for the clarification! Was troubled by this question. :slight_smile:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.