Python 3.x error with methods asking for input error is TypeError: __init__() takes 0 positional arguments but 1 was given

Python 3.x error with methods asking for input error is TypeError: __init__() takes 0 positional arguments but 1 was given

我正在尝试使用 TeamTreehouse 学习订阅和这本 Starting Out With Programming Logic And Design(第 3 版)一书来尝试学习编程和 Python。请不要开枪打死我我正在学习

目标: 我正在尝试将宠物 class 设置为 3 fields/attributes/properties。对于每个 field/attribute/property,class 将有 2 个方法,set 和 get。我试图弄清楚如何让每个方法(它仍然是它的根函数)来询问用户的输入,然后将内部属性设置为输入值。

研究和故障排除: 当我不要求用户输入数据作为 class 方法的一部分时,我可以运行 无错误. http://repl.it/oIr/3

我已经参考了 "cheat sheet" 了解 OOP 的外观。 http://www.newthinktank.com/2014/11/python-programming/

这是我翻阅的文档,它似乎是 OOP 的 2.x python 版本参考,但它并没有对缓解或改变我的头痛起到多大作用。

我在发帖前发现了这份文件,这让我的头脑开始变得清晰起来。可能我需要 clean/scrub 所有通过 value/reference 编码然后重写? How to get user input within a Method (python)

错误:

Traceback (most recent call last):
  File "python", line 43, in <module>
TypeError: __init__() takes 0 positional arguments but 1 was given

代码: http://repl.it/oIr/5

# Create class for Pet

class Pet:
    __name = ""
    __species = ""
    __age = ""

    # Object constructor
    def __init__():
        self.__name = name
        self.__species = species
        self.__age = age

    #Methods    
    def setName(self):
        self.__name =input("What is your pet's name?\n")

    def setSpecies(self, species):
        self.__species=input("What type of pet is it?\n")

    def setAge(self, age):
        self.__age=input("How old is your pet?\n")

    def getName(self):
        return self.__name

    def getSpecies(self):
        return self.__species

    def getAge(self):
        return self.__age

    def get_type(self):
        print("Pet")

    def toString(self):
        return"{} is a {} and is {} years old".format(self.__name,self.__species,self.__age)

#name=input("What is your pet's name?\n")
#species=input("What type of pet is it?\n")
#age=input("How old is your pet?\n")

myPet=Pet()
myPet.setName()

#myPet=Pet(name,species,age)
print(myPet.toString())

Python 中的所有方法都采用 self 参数。您的 __init__ 方法没有:

def __init__():

但Python仍在尝试提供一个:

TypeError: __init__() takes 0 positional arguments but 1 was given

添加self参数:

def __init__(self):

您的下一个问题是您的 __init__ 方法期望变量 namespeciesage 可用,但您从未设置这些变量:

def __init__(self):
    self.__name = name
    self.__species = species
    self.__age = age

也许您打算制作这些方法参数:

def __init__(self, name, species, age):
    self.__name = name
    self.__species = species
    self.__age = age

这意味着您只能通过包含这些值来创建新的 Pet() 实例:

name = input("What is your pet's name?\n")
species = input("What type of pet is it?\n")
age = input("How old is your pet?\n")

myPet = Pet(name, species, age)