我不断收到错误消息
NameError: name animal_type is not defined
要么
TypeError: __init__() missing 2 required positional arguments: 'animal_type' and 'name'
不管我把线改成
animal = Animal.Animal(animal_type, animal)
要么
animal = Animal.Animal()
稍后有:
#Add animal to list
def addAnimal(animal):
atype = input("What type of animal would you like to create? ")
theAnimal = atype
theAnimal = Animal.Animal()
theAnimal.set_animal_type(atype)
aname = input("What is the animal's name? ")
theName = aname
theName = Animal.Animal()
theName.set_name(aname)
zookeeper.add_animal(theAnimal, theName)
为了提供一些背景信息,该程序将导入2个类。
这是我正在呼叫的一个:
import random
class Animal:
#initialize attributes
def __init__(self,animal_type, name, mood = None):
self.__animal_type = animal_type
self.__name = name
if mood:
self.__mood = mood
else:
self.check_mood()
# set methods
def set_animal_type(self, animal_type):
self.__animal_type = animal_type
def set_name(self, name):
self.__name = name
最佳答案
之所以得到NameError
,是因为在第二个文件(要将Animal
类导入到的文件)中,您尚未定义变量。
animal = Animal.Animal(animal_type, animal)
animal_type
和/或animal
尚未定义。至于
TypeError
的问题animal = Animal.Animal()
是您没有传递任何必需的变量。
animal_type
和animal
。例如:
import Animal # Animal.py
atype = 'Snake'
name = 'George'
a = Animal.Animal(atype, name)
或者简单地
import Animal # Animal.py
a = Animal.Animal('Snake', 'George')
其他问题(编辑后):
1.)
set_name
或set_animal_type
时不需要创建新的类实例。 (在addAnimal
中)您应该做的是这样的:
theAnimal = Animal.Animal(atype, aname)
2.)
您需要先拥有
input
。像这样:def addAnimal(animal):
atype = input("What type of animal would you like to create? ")
aname = input("What is the animal's name? ")
theAnimal = Animal.Animal(atype, aname)
theAnimal.set_animal_type(atype)
theAnimal.set_name(aname)
zookeeper.add_animal(theAnimal, aname)
3.)
您的
addAnimal
函数不需要任何变量。不使用它们。def addAnimal(animal):
应该
def addAnimal():