Search code examples
python-3.xmethodsaccessor

Can't correctly call accessor method of class in Python


Here is the code

import random


class Animal(object):
    __name = ""
    __animal_type = ""
    __mood = 0

    def __init__(self, animal_type, animal_name):
        self.__animal_type = animal_type
        self.__name = animal_name
        self.__mood = random.randint(1, 3)

    def get_animal_type(self, animal):
        return self.__animal_type

    def get_name(self, animal):
        return self.__name

    def check_mood(self, animal):
        animal_mood = ""
        if self.__mood == 0:
            animal_mood = "the mood was 0 and didn't change"
        elif self.__mood == 1:
            animal_mood = "happy"
        elif self.__mood == 2:
            animal_mood = "hungry"
        elif self.__mood == 3:
            animal_mood = "sleepy"
        return animal_mood


animal_list = [Animal]
do_animal_creation = True
while do_animal_creation:
    print("Welcome to animal gen")

    new_animal_type = input("What type of animal? ")
    new_animal_name = input("Name of animal? ")

    new_animal = Animal(new_animal_type, new_animal_name)
    animal_list.append(new_animal)

    do_animal_creation = input("Add another animal? y/n: ")

    if do_animal_creation != 'y':
        do_animal_creation = False
        print("\nThanks for using this program.")
    else:
        do_animal_creation = True
print("Animal list:")
for item in animal_list:
    item_name = item.get_name(item)
    item_type = item.get_animal_type(item)
    item_mood = item.check_mood(item)
    print(item_name + " the " + item_type + " is " + item_mood + ".")

Everytime I try to call the get_name or get_animal_type or check_mood methods it tells me I'm sending an incorrect amount of parameters. Then I try to play with the parameters, either send one more like it asks me to, or take away a parameter in the method definition within the class, and neither of those work. I feel like I am syntactically not calling the methods correctly, but I don't know what exactly I'm doing wrong.


Solution

  • The first element of your animal_list is the Animal class, not an instance. Hence, calling instance methods on it won't work as expected. Whatever you might have tried to make that work (like passing an instance as first argument) will then fail for the subsequent elements which are instances.

    Change

    animal_list = [Animal]  
    # this puts the Animal class in your list
    # Note: In Python, lists are not type-parametrized like in other languages,
    # which is probably what you assumed you were doing
    

    to

    animal_list = []
    

    Moreover, your getters should not take parameters:

    def get_animal_type(self):
        return self.__animal_type
    

    and call it:

    item.get_animal_type()