[英]How to initialize subclass parameters in python using super()
I have seen various examples on How to use 'super' in python , but in all of these examples, there are no arguments being passed to the subclass' init method. 我已经看到了关于如何在python中使用'super'的各种示例,但在所有这些示例中,没有参数传递给子类的init方法。 Consider the following example. 请考虑以下示例。
Here is the base class: 这是基类:
class Animal(object):
def __init__(self, genus):
self.genus = genus
Now heres without using super: 现在heres没有使用超级:
class Dog(Animal):
def __init__(self, genus):
Animal.__init__(self, genus)
x = Dog('Canis')
print x.genus # Successfully prints "Canis"
Now when I use super instead: 现在,当我使用super时:
class Dog(Animal):
def __init__(self, genus):
super(Animal, self).__init__(genus)
x = Dog('Canis')
print x.genus
I get the following error: 我收到以下错误:
TypeError: object.__init__() takes no parameters
So then if object. 那么如果对象。 init () takes no parameters, how to I set the specific genus of this particular animal when instantiated that subclass? init ()不带参数,如何在实例化那个子类时设置这个特定动物的特定属? Do I have to explicitly assign the variables like this: 我是否必须显式分配这样的变量:
class Dog(Animal):
def __init__(self, genus):
super(Animal, self).__init__()
self.genus = genus
Write: 写:
class Dog(Animal):
def __init__(self, genus):
super(Dog, self).__init__(genus)
So instead of: 所以代替:
super(Animal, self).__init__(genus)
use: 采用:
super(Dog, self).__init__(genus)
Think of: What is the super class of Dog
? 想一想:什么是超级Dog
? Animal
would be the right answer to this questions for this case. 对于这个案例, Animal
将是这个问题的正确答案。 But if you use multiple inheritance this can be different. 但是如果你使用多重继承,这可能会有所不同。
If you use Python 3, all things get simpler: 如果您使用Python 3,所有事情都会变得更简单:
class Dog(Animal):
def __init__(self, genus):
super().__init__(genus)
works. 作品。 Much less surface for making a mistake. 犯错的表面要少得多。
If you need to work with Python 2, consider Python-Future . 如果您需要使用Python 2,请考虑使用Python-Future 。 Than you can do this on Python 2: 你可以在Python 2上做到这一点:
from builtins import object, super
class Animal(object):
def __init__(self, genus):
self.genus = genus
class Dog(Animal):
def __init__(self, genus):
super().__init__(genus)
x = Dog('Canis')
print(x.genus)
This builtins
module comes from Python-Future. 这个builtins
模块来自Python-Future。 Using it, allows you to program Python 3 in Python 2 (at least for all important changes). 使用它,允许您在Python 2中编写Python 3(至少对于所有重要的更改)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.