python速成课程:Ch9创建类\uuuDog examp

2024-03-28 12:59:06 发布

您现在位置: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.")

输出:

 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

Tags: to代码nameinselfagetitleis
1条回答
网友
1楼 · 发布于 2024-03-28 12:59:06

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

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以双下划线开始和结束。你知道吗

相关问题 更多 >