
一:super()
super方法
super方法是Python中的一个常用内置方法,它用来帮助我们调用父类中的方法,从而实现向前兼容,Python官方文档中对super方法的解释是:
1
|
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.
|
意思是,它代表我们调用父类中的方法。
在没有super方法时,我们用以下方式调用super方法:
1
|
class A(object):
|
以上调用方式,我们需要用父类的类名直接调用父类中的方法,并将当前类(子类)的实例对象传递给父类(类方法和静态方法等不需要传self的方法除外)。
而如果使用Python2中的super方法,我们可以将以上调用方式,改为如下形式:
1
|
class A(object):
|
注意,必须在父类中继承object对象。
如果使用Python3中的super方法,我们可以进一步将调用方式,简写为如下形式:
1
|
class A(object):
|
可以看到,我们不需要再将子类和实例对象传给super方法了,写法更加简洁。
下面看一下多继承
1
|
class A(object):
|
执行结果如下:
1
|
D.foo
|
可见,查找顺序也是根据D类的mro列表中的顺序来的。
classmethod的调用方式也类似,下面分别是Python2和python3中classmethod的调用方式:
Python2:
1
|
class A(object):
|
Python3
1
|
class A(object):
|
注意,因为直接使用类调用classmethod,所以没有实力对象,在使用Python2调用时,super方法的参数可以类名和cls的任意组合,比如, super(B, cls)、super(B, B)、super(cls, B)、super(cls, cls),建议使用super(B, cls)。
浙公网安备 33010602011771号