简体   繁体   English

使用super的构造函数的子类构造函数

[英]subclass constructor using super's constructor

Initially this was defined 最初定义了这个

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

    def get_name(self):
        return self.name

    def say(self):
        return("What does the " + self.name + " says")

but now we want to create subclasses of Mammals, whose constructor will call the Mammal's constructor with the correct name. 但现在我们要创建Mammals的子类,其构造函数将使用正确的名称调用Mammal的构造函数。

  class Dog(Mammal):
        def __init__(self):
            Dog.self

This is my code. 这是我的代码。 It says type object 'Dog' has no attribute 'self' what's the problem? 它说type object 'Dog' has no attribute 'self'什么问题?

when print(Dog().get_name()) I should get Dog. 什么时候print(Dog().get_name())我应该得到狗。

If you are using Python 2.x, you should write 如果你使用的是Python 2.x,你应该写

super(Dog, self).__init__('name')

or, for Python 3: 或者,对于Python 3:

super().__init__('name')

instead of 代替

Dog.self

See Understanding Python super() with __init__() methods for detail. 有关详细信息,请参阅使用__init __()方法了解Python super()

If you want Dog().get_name() to return 'Dog', you should call 如果你想让Dog().get_name()返回'Dog',你应该打电话

super(Dog, self).__init__('Dog')

You should write like this: 你应该这样写:

class Dog(Mammal):
    def __init__(self):
        super().__init__('dog name')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从子类调用超类构造函数的原因? - Reason for calling super class constructor from subclass? 将所需的位置参数传递给超类,而无需将其添加到子类的构造函数中 - Pass required positional argument to super class without adding it in subclass' constructor 在 ForceElement 的子类上调用 super().__init__() 导致未定义构造函数 - Calling super().__init__() on subclass of ForceElement causes No constructor defined 返回之前在子类的构造函数中包装实例 - Wrapping an instance in a subclass's constructor before returning 在枚举构造函数中使用super()时的NameError - NameError when using super() in enum constructor 在 OrderedDict 子类中覆盖没有 super() 的 __init__ 但父构造函数仍然有效 - Overwriting __init__ without super() in OrderedDict subclass but parent constructor still works Python Django-models.Model子类的构造函数 - Python Django - models.Model subclass's constructor 在Python 3中,超类可以多态调用子类的构造函数 - in Python 3, can a superclass polymorphically call a subclass's constructor 使用 super() 时未调用 Python 多个 inheritance 构造函数 - Python multiple inheritance constructor not called when using super() 使用 super() 调用父 class 构造函数与使用父 class 名称 - Calling a Parent class constructor with super() vs using Parent class name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM