开发者社区> 问答> 正文

无法正确调用Python中的类的访问器方法

这是代码

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 + ".")

每当我尝试调用get_nameget_animal_typecheck_mood方法时,都会告诉我我发送了不正确的参数。然后,我尝试使用参数,或者像它要求的那样发送一个参数,或者在类中的方法定义中删除一个参数,而这些都不起作用。我觉得我在语法上没有正确调用方法,但是我不知道我到底在做什么错。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 21:37:07 520 0
1 条回答
写回答
取消 提交回答
  • 您的animal_list的第一个元素是Animal类,而不是实例。因此,在其上调用实例方法将无法正常工作。无论您尝试进行何种工作(例如将实例作为第一个参数传递),对于随后的实例元素都将失败。

    更改

    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
    

    animal_list = []
    

    此外,您的吸气剂不应使用参数:

    def get_animal_type(self):
        return self.__animal_type
    

    并称之为:

    item.get_animal_type()
    

    回答来源:stackoverflow

    2020-03-24 21:37:13
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载