为了调用父类(超类)的一个方法,可以使用 super() 函数,比如
# -*- coding: utf-8 -*- """ @Time: 2018/4/16 @Author: songhao @微信公众号: zeropython @File: d.py """ class One(object): def new_one(self): print("new_one func") class Two(One): def __init__(self): <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/super" title="View all posts in super" target="_blank">super</a></span>().new_one() def new_two(self): print("newtp") <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/super" title="View all posts in super" target="_blank">super</a></span>().new_one() if __name__ == '__main__': t = Two() t.new_two() """ 显示的结果是: new_one func newtp new_one func """
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
# -*- coding: utf-8 -*-
"""
@Time: 2018/4/16
@Author: songhao
@微信公众号: zeropython
@File: d.py
"""
class
One
(
object
)
:
def
new_one
(
self
)
:
print
(
"new_one func"
)
class
Two
(
One
)
:
def
__init__
(
self
)
:
super
(
)
.
new_one
(
)
def
new_two
(
self
)
:
print
(
"newtp"
)
super
(
)
.
new_one
(
)
if
__name__
==
'__main__'
:
t
=
Two
(
)
t
.
new_two
(
)
"""
显示的结果是:
new_one func
newtp
new_one func
"""
|
super() 函数的一个常见用法是在 __init__() 方法中确保父类被正确的初始化了:
class A: def __init__(self): self.x = 0 class B(A): def __init__(self): super().__init__() self.y = 1
1
2
3
4
5
6
7
8
|
class
A
:
def
__init__
(
self
)
:
self
.
x
=
0
class
B
(
A
)
:
def
__init__
(
self
)
:
super
(
)
.
__init__
(
)
self
.
y
=
1
|
super() 的另外一个常见用法出现在覆盖Python特殊方法的代码中,比如:
class Proxy: def __init__(self, obj): self._obj = obj # Delegate attribute lookup to internal obj def __getattr__(self, name): return getattr(self._obj, name) # Delegate attribute assignment def __setattr__(self, name, value): if name.startswith('_'): super().__setattr__(name, value) # Call original __setattr__ else: setattr(self._obj, name, value)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class
Proxy
:
def
__init__
(
self
,
obj
)
:
self
.
_obj
=
obj
# Delegate attribute lookup to internal obj
def
__getattr__
(
self
,
name
)
:
return
getattr
(
self
.
_obj
,
name
)
# Delegate attribute assignment
def
__setattr__
(
self
,
name
,
value
)
:
if
name
.
startswith
(
'_'
)
:
super
(
)
.
__setattr__
(
name
,
value
)
# Call original __setattr__
else
:
setattr
(
self
.
_obj
,
name
,
value
)
|
在上面代码中,__setattr__() 的实现包含一个名字检查。 如果某个属性名以下划线(_)开头,就通过 super() 调用原始的 __setattr__() , 否则的话就委派给内部的代理对象 self._obj 去处理。 这看上去有点意思,因为就算没有显式的指明某个类的父类, super() 仍然可以有效的工作。