Python 3 - 不错
在 Python 3 中,这是有效的:
class Vehicle:
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super().__init__()
car = Car()
prints:
Vehicle __init__() called
Python 2 - 更多工作
在 Python 2 中尝试同样的事情会导致问题:
class Vehicle:
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super().__init__()
car = Car()
抛出这个异常:
Traceback (most recent call last):
...
TypeError: super() takes at least 1 argument (0 given)
我们需要提供自己的类作为第一个和self
作为第二个参数super()
:
class Vehicle:
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super(Car, self).__init__()
car = Car()
但这还不够:
Traceback (most recent call last):
...
TypeError: must be type, not classobj
class Vehicle:
创建一个旧式类。Vehicle
必须继承自object
获得一个可以使用的新式类super()
:
class Vehicle(object):
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super(Car, self).__init__()
car = Car()
prints:
Vehicle __init__() called
Python 2 中不带参数的 super()
必须一直记住这两个论点有点烦人。幸运的是,有一个解决方案。强烈推荐的图书馆Python-未来 http://python-future.org允许您使用super()
Python 2 中没有参数:
from builtins import object, super # from Python-Future
class Vehicle(object):
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super().__init__()
car = Car()
prints:
Vehicle __init__() called