eTypeError:__ init __()缺少1个必需的位置参数:'键入'

时间:2015-04-17 00:07:47

标签: python class

我有两个程序。 第一个是animalGenerator.py:

# This program generates a name and an animal type

import Animals

print("Welcome to the animal generator!")
print("This program creates Animal objects")


def main():

    animals = make_list()

    print("\nAnimal List")
    print("-------------")

    display_list(animals)

def make_list():

    animal_list = []

    again = 'y'

    while again.lower() == 'y':

        typ = input("\nWhat type of animal would you like to create? ")

        nam = input("What is the animal's name? ")

        ani = Animals.Animal(typ, nam)

        animal_list.append(ani)

        again = input("\nWould you like to add more animals (y/n)? ")

    return animal_list

def display_list(animal_list):
    for item in animal_list:
        print("\n" + item.get_name() + "the" + item.get_Type() + "is" + item.get_mood())

main()

第二个程序Animals.py:

import random

class Animal:

def __init__(self, name, mood, Type):

    self.__name = name
    self.__mood = mood
    self.__animal_type = Type

def set_name(self, name):

    self.__name = name

def set_mood(self, mood):

    self.__mood = mood

def set_animal_type(self, Type):

    self.__animal_type = Type

def toss(self):

    if random.randint(1, 2, 3) == 1:
        self.__mood = 'Happy'
    elif random.randint(1, 2, 3) == 2:
        self.__mood = 'Hungry'
    elif random.randint(1, 2, 3) == 3:
        self.__mood = 'Sleepy'

def get_name(self):

    return self.__name

def get_mood(self):

    return self.__mood

def get_animal_type(self):

    return self.__animal_type                 

运行第一个程序时收到错误(标题) 这是追溯:

Traceback (most recent call last):
  File "C:\Users\Dahlia\Desktop\McCuneShannonAnimals\animalGenerator.py", line 42, in <module>
    main()
  File "C:\Users\Dahlia\Desktop\McCuneShannonAnimals\animalGenerator.py", line 11, in main
    animals = make_list()
  File "C:\Users\Dahlia\Desktop\McCuneShannonAnimals\animalGenerator.py", line 30, in make_list
    ani = Animals.Animal(typ, nam)
TypeError: __init__() missing 1 required positional argument: 'Type'

有人可以帮我弄清楚如何/为什么“Type”缺少位置参数?

2 个答案:

答案 0 :(得分:1)

您将Animals&n; __init__()定义为def __init__(self, name, mood, Type)。但是,你用ani = Animals.Animal(typ, nam)称呼它 - 这是预期的三个中的两个参数。确保正确定义每个方法,并根据其定义始终正确调用方法。

答案 1 :(得分:-1)

第二个程序看起来不像有效的python,缺少一定程度的缩进,所以我很惊讶这实际上是在运行。

但是,对于原始问题 - 您使用(typ, nam)实例化Animal,但是在构造函数中它还需要第三个参数 - Type - (name, mood, Type) - 这是位置参数口译员在抱怨。