【问题标题】:Can't correctly call accessor method of class in Python无法在 Python 中正确调用类的访问器方法
【发布时间】:2020-03-06 17:08:44
【问题描述】:

这里是代码

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

【问题讨论】:

  • 请包含完整错误信息。
  • 为什么你所有的get 方法都需要两个参数?

标签: python-3.x methods accessor


【解决方案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 = []

此外,你的 getter 不应该带参数:

def get_animal_type(self):
    return self.__animal_type

然后调用它:

item.get_animal_type()

【讨论】:

  • 这修复了它。非常感谢您的帮助。
猜你喜欢
  • 2013-03-20
  • 2018-11-18
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 2015-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多