python速成班:第9章-创建class_ dog示例

时间:2018-10-28 17:31:06

标签: python python-3.x class instance

您好,我无法弄清楚以下代码产生错误消息时我在做错什么,我已经从网络上复制并粘贴了相同的代码,它工作得很好,但是当我键入时定义的类似乎没有参数。

输入:

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

1 个答案:

答案 0 :(得分:2)

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

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中的许多special names以双下划线开头和结尾。