python速成课程:第9章-创建类狗示例

python速成课程:第9章-创建类狗示例,python,python-3.x,class,instance,Python,Python 3.x,Class,Instance,您好,我很难找出以下代码产生错误消息的错误,我已经从web复制并粘贴了相同的代码,它工作正常,但当我键入它时,定义的类似乎不带参数 输入: class Dog(): """A simple attempt to model a dog""" def _init_(self, name, age): """initialize name and age attributes.""" self.name = name self.age = age def sit

您好,我很难找出以下代码产生错误消息的错误,我已经从web复制并粘贴了相同的代码,它工作正常,但当我键入它时,定义的类似乎不带参数

输入:

class Dog():
  """A simple attempt to model a dog"""
  def _init_(self, name, age):
    """initialize name and age attributes."""
    self.name = name
    self.age = age

  def sit(self):
    """simulate dog sitting in response to a command"""
    print(self.name.title() + " is now sitting.")

  def roll_over(self):
    """simulate rolling over in response to a command"""
    print(self.name.title() + " rolled over!")

my_dog = Dog('willie', 6)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
输出:

 Traceback (most recent call last):
  File "C:/Users/sstie/Desktop/python_work/ch.9_retry.py", line 16, in <module>
    my_dog = Dog('willie', 6)
TypeError: Dog() takes no arguments
回溯(最近一次呼叫最后一次):
文件“C:/Users/sstie/Desktop/python\u work/ch.9\u retry.py”,第16行,在
我的狗=狗(“威利”,6)
TypeError:Dog()不接受任何参数

构造函数名称中需要两个下划线:

class Dog:
    """A simple attempt to model a dog"""
    def __init__(self, name, age):
        """initialize name and age attributes."""
        self.name = name
        self.age = age

    def sit(self):
        """simulate dog sitting in response to a command"""
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        """simulate rolling over in response to a command"""
        print(self.name.title() + " rolled over!")

my_dog = Dog('willie', 6)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")

python中的许多函数都以双下划线开头和结尾。

构造函数名称中需要两个下划线:

class Dog:
    """A simple attempt to model a dog"""
    def __init__(self, name, age):
        """initialize name and age attributes."""
        self.name = name
        self.age = age

    def sit(self):
        """simulate dog sitting in response to a command"""
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        """simulate rolling over in response to a command"""
        print(self.name.title() + " rolled over!")

my_dog = Dog('willie', 6)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")

python中的许多代码都以双下划线开头和结尾。

\u init\u
还需要两个下划线。您的缩进是错误的。
\u init\u
还需要两个下划线。您的缩进是错误的。