【问题标题】:How to resolve __init__() taking 1 argument when 2 are given amid child classes?当在子类中给出 2 个参数时,如何解决 __init__() 带 1 个参数?
【发布时间】:2018-03-09 07:42:23
【问题描述】:

我使用的是 python 2.7,我创建了一个 Dog 父类和一个 Cat 子类;我已经将 Cat 类“分解”为两部分,这两个部分本来是要链接在一起的,但是却抛出了一个错误:

关于如何解决这个问题的任何想法,以及这里传递参数的逻辑?:

class Dog(object):
    def __init__(self, name):
        self.name = name
        self.age = 6
    def age_update(self, age_update):
        self.age+=age_update
        print("new age: " + str(self.age))
    def speak (self):
        print("My name is "+ self.name + "and I'm "+ str(self.age))

class Cat(Dog): 
    def __init__(self):
        super(Cat, self).__init__(name)
        self.lives=CatNature()

class CatNature(Cat): 
    def __init__(self, lives=9):
        self.lives=lives

    def show_lives(self): 
        print("This cat has " + str(self.lives) + " lives")


cat1 = Cat("Fuzz")
print ("Cat's name is " + cat1.name + " and " + str(cat1.age))

cat1.lives.show_lives()

错误:

Traceback (most recent call last):
  File "/Users/.../Python_experiments/class.py", line 27, in <module>
    cat1 = Cat("Fuzz")
TypeError: __init__() takes exactly 1 argument (2 given)

【问题讨论】:

  • 猫就是狗?
  • ;-) 是的,我在命名类时很仓促。为了这个实验,我的想法是猫和狗都可以共享有名字和年龄的品质......并且被错误分心而无法回到那个问题 - 我会研究你的解决方案 - 并做出回应有任何其他问题 - 谢谢!

标签: python python-2.7 class arguments


【解决方案1】:

首先,我觉得将Dog 子类化为Cat 有点奇怪,但话虽如此,Cat__init__ 方法缺少name 参数

class Cat(Dog): 
    def __init__(self, name):
        super(Cat, self).__init__(name)
        self.lives=CatNature()

这很重要,因为您将 name 传递给超类的 __init__

此外,CatNatureCat 的子类很奇怪,因为它不是动物,而且您不调用超级 __init__ 函数。无论如何,你不能调用父类的__init__ 方法,否则你会陷入无限递归:每个CatNature 构造一个新的CatNature,这将一直持续到我们得到堆栈溢出或内存累死了。

更好的建模可能是:

class Animal(object):
    def __init__(self, name):
        self.name = name
        self.age = 6
    def age_update(self, age_update):
        self.age+=age_update
        print("new age: " + str(self.age))
    def speak (self):
        print("My name is "+ self.name + "and I'm "+ str(self.age))

class Cat(Animal): 
    def __init__(self, name):
        super(Cat, self).__init__(name)
        self.lives=CatNature()

class CatNature(object): 
    def __init__(self, lives=9):
        self.lives=lives

    def show_lives(self): 
        print("This cat has " + str(self.lives) + " lives")

【讨论】:

    猜你喜欢
    • 2020-01-19
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 2017-04-22
    • 2017-11-23
    • 2016-02-28
    相关资源
    最近更新 更多