【问题标题】:Python 3.x Beginner: TypeError: dog() takes no argumentsPython 3.x 初学者:TypeError:dog() 不接受任何参数
【发布时间】:2019-07-14 10:49:29
【问题描述】:
class animal(object):
    def __init__(self,name):
        self.name = name

    def eat(self,food):
        print("{} is eating".format(self.name,food))


class dog():

    def fetch(self,thing):
        print("{} get the {}".format(self.name,thing))

s = dog('r')

错误:回溯(最近一次调用最后一次):文件 “C:\EclipseWorkspaces\csse120\LearnPython\inheritance.py”,第 14 行,在 s = dog('r') TypeError: dog() 没有参数

Cant figure out whats wrong, please help.

【问题讨论】:

  • 看起来像一个继承练习。 :-) 也许你忘了继承class dog

标签: python


【解决方案1】:

你错过了狗继承动物的形式

class Animal(object):
    def __init__(self,name):
        self.name = name


    def eat(self,food):
        print("{} is eating".format(self.name,food))


class Dog(Animal):

    def fetch(self,thing):
        print("{} get the {}".format(self.name,thing))

s = Dog('r')

【讨论】:

  • 我认为s = dog('dog') 应该在类狗块之外。不是吗?
【解决方案2】:

由于您的错误表明您正在尝试通过将“r”参数传递给 Dog 类构造函数来创建 Dog 类的对象。但是 Dog 类没有接受 char 或字符串文字作为参数的构造函数。看来您正在尝试使用 Animal 类构造函数来创建 Dog 对象(Dogs 是 Animal 类的子类)

class animal(object):
  def __init__(self,name):
      self.name = name

要解决这个错误,你应该首先继承 Dog 类,然后创建一个 Dog 对象。 继承 Animal 类,

class dog(animal):
  def fetch(self,thing):
      print("{} get the {}".format(self.name,thing))

现在您可以使用 Animal 类构造函数并使用 s = dog('r') 语句创建 Dog 对象。

提示:- 我认为按照PEP8 样式约定中所述,从一开始就对类名使用 CapWords 约定是很好的。

【讨论】:

    【解决方案3】:

    发布答案有点晚,但请尝试在 init 的每一侧添加两个下划线,
    不是

     _init_ 
    

    应该是

    __init__
    
    class animal(object):
        def __init__(self,name):
            self.name = name
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-08
      • 2017-09-20
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多