最近很多小伙伴都在问python的super使用和python中的super这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展pythonsupervisor使用、Python-Py
最近很多小伙伴都在问python的super使用和python中的super这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展python supervisor使用、Python-Python的super()如何处理多重继承?、Python3中的super()函数详解、python3的super详解等相关知识,下面开始了哦!
本文目录一览:- python的super使用(python中的super)
- python supervisor使用
- Python-Python的super()如何处理多重继承?
- Python3中的super()函数详解
- python3的super详解
python的super使用(python中的super)
本文讲述一下super的使用:
1:
class A(object):
def __init__():
print "I''m A"
def test(self):
print "I''m test"
class B(A):
def __init__():
super(B,self).__init__()
def test_B(self):
super(B,self).test()
b=B()
b.test_B()
运行结果:
这是简单的调用
当调用父类比较多的时候,在调用方法是遵循MRO C3线性处理法则,源码如下:
#-*- encoding:GBK -*-#
def mro_C3(*cls):
print len(cls)
if len(cls)==1:
print "hello"
if not cls[0].__bases__:
print cls
return cls
else:
return cls+ mro_C3(*cls[0].__bases__)
else:
seqs = [list(mro_C3(C)) for C in cls ] +[list(cls)]
res = []
while True:
non_empty = list(filter(None, seqs))
if not non_empty:
return tuple(res)
for seq in non_empty:
candidate = seq[0]
not_head = [s for s in non_empty if candidate in s[1:]]
if not_head:
candidate = None
else:
break
if not candidate:
raise TypeError("inconsistent hierarchy, no C3 MRO is possible")
res.append(candidate)
for seq in non_empty:
if seq[0] == candidate:
del seq[0]
class C(object):
pass
class A(C):
pass
class B(C):
pass
mro_C3(A,B)
简单的讲述一下:
#!/usr/bin/env python
#--*-- coding: utf-8 --*--
class A(object):
def __init__(self):
print "enter A"
print "leave A"
class C(A):
def __init__(self):
print "enter C "
super(C,self).__init__()
def c(self):
print "diaoyongfangfa"
class B(A):
def __init__(self):
print "enter B"
super(B,self).__init__()
class D(B,C):
def __init__(self):
super(D,self).__init__()
print "leave D"
b = D()
结果:enter B
enter C
enter A
leave A
leave D
>>>
在调用的时候首先mro(A)=[A,O]
mro[B]=[B]+merge(mro(A)+[A])
=[B]+merge([A,O]+[A])
遍历执行merge操作的序列,如果一个序列的第一个元素,是其他序列中的第一个元素,或不在其他序列出现,则从所有执行merge操作序列中删除这个元素,合并到当前的mro中。
所以mro[B]=[B,A]+merge([O])=[B,A,O],同理mro[C]=[C,A,O]
mro[D]=[D]+merge(mro(B)+mro(C)+[B,C])
=[D]+merge([B,A,O]+[C,A,O]+[B,C])
=[D,B,C]+merge([A,O]+[A,O])
=[D,B,C,A]+merge([O]+[O])
=[D,B,C,A]
所以多父类的时候就遵循这个方式
python supervisor使用
Supervisor 是基于 Python 的进程管理工具,只能运行在 Unix-Like 的系统上,也就是无法运行在 Windows 上。Supervisor 官方版目前只能运行在 Python 2.4 以上版本,但是还无法运行在 Python 3 上,不过已经有一个 Python 3 的移植版 supervisor-py3k。
什么情况下我们需要进程管理呢?就是执行一些需要以守护进程方式执行的程序,比如一个后台任务,我最常用的是用来启动和管理基于 Tornado 写的 Web 程序。
除此之外,Supervisor 还能很友好的管理程序在命令行上输出的日志,可以将日志重定向到自定义的日志文件中,还能按文件大小对日志进行分割。
Supervisor 有两个主要的组成部分:
supervisord
,运行 Supervisor 时会启动一个进程 supervisord,它负责启动所管理的进程,并将所管理的进程作为自己的子进程来启动,而且可以在所管理的进程出现崩溃时自动重启。supervisorctl
,是命令行管理工具,可以用来执行 stop、start、restart 等命令,来对这些子进程进行管理。
安装
sudo pip install supervisor
创建配置文件
echo_supervisord_conf > /etc/supervisord.conf
如果出现没有权限的问题,可以使用这条命令
sudo su - root -c "echo_supervisord_conf > /etc/supervisord.conf"
配置文件说明
想要了解怎么配置需要管理的进程,只要打开 supervisord.conf 就可以了,里面有很详细的注释信息。
打开配置文件
vim /etc/supervisord.conf
默认的配置文件是下面这样的,但是这里有个坑需要注意,supervisord.pid 以及 supervisor.sock 是放在 /tmp 目录下,但是 /tmp 目录是存放临时文件,里面的文件是会被 Linux 系统删除的,一旦这些文件丢失,就无法再通过 supervisorctl 来执行 restart 和 stop 命令了,将只会得到unix:///tmp/supervisor.sock
不存在的错误 。
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 35 36 37 38 39 |
[unix_http_server] ;file=/tmp/supervisor.sock ; (the path to the socket file) ;修改为 /var/run 目录,避免被系统删除 file=/var/run/supervisor.sock ; (the path to the socket file) ;chmod=0700 ; socket file mode (default 0700) ;chown=nobody:nogroup ; socket file uid:gid owner ;username=user ; (default is no username (open server)) ;password=123 ; (default is no password (open server)) ;[inet_http_server] ; inet (TCP) server disabled by default ;port=127.0.0.1:9001 ; (ip_address:port specifier, *:port for ;all iface) ;username=user ; (default is no username (open server)) ;password=123 ; (default is no password (open server)) ... [supervisord] ;logfile=/tmp/supervisord.log ; (main log file;default $CWD/supervisord.log) ;修改为 /var/log 目录,避免被系统删除 logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log) logfile_maxbytes=50MB ; (max main logfile bytes b4 rotation;default 50MB) logfile_backups=10 ; (num of main logfile rotation backups;default 10) loglevel=info ; (log level;default info; others: debug,warn,trace) ;pidfile=/tmp/supervisord.pid ; (supervisord pidfile;default supervisord.pid) ;修改为 /var/run 目录,避免被系统删除 pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid) ... ;设置启动supervisord的用户,一般情况下不要轻易用root用户来启动,除非你真的确定要这么做 ;user=chrism ; (default is current user, required if root) ... [supervisorctl] ; 必须和''unix_http_server''里面的设定匹配 ;serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL for a unix socket ;修改为 /var/run 目录,避免被系统删除 serverurl=unix:///var/run/supervisor.sock ; use a unix:// URL for a unix socket ;serverurl=http://127.0.0.1:9001 ; use an http:// url to specify an inet socket ;username=chris ; should be same as http_username if set ;password=123 ; should be same as http_password if set ... |
默认情况下,进程的日志文件达到50MB时,将进行分割,最多保留10个文件,当然这些配置也可以对每个进程单独配置。
权限问题
设置好配置文件后,应先创建上述配置文件中新增的文件夹。如果指定了启动用户 user,这里以 oxygen 为例,那么应注意相关文件的权限问题,包括日志文件,否则会出现没有权限的错误。例如设置了启动用户 oxygen,然后启动 supervisord 出现错误
Error: Cannot open an HTTP server: socket.error reported errno.EACCES (13)
就是由于上面的配置文件中 /var/run 文件夹,没有授予启动 supervisord 的用户 oxygen 的写权限。/var/run 文件夹实际上是链接到 /run,因此我们修改 /run 的权限。
sudo chmod 777 /run
这样有点简单粗暴,也可以考虑把上述配置文件中 .sock
,.pid
等文件修改到其他文件夹中,并确保有相应的权限即可。一般情况下,我们可以用 root 用户启动 supervisord 进程,然后在其所管理的进程中,再具体指定需要以那个用户启动这些进程。
使用浏览器来管理
supervisor 同时提供了通过浏览器来管理进程的方法,只需要注释掉如下几行就可以了。
1 2 3 4 5 6 7 8 9 10 |
;[inet_http_server] ; inet (TCP) server disabled by default ;port=127.0.0.1:9001 ; (ip_address:port specifier, *:port for ;all iface) ;username=user ; (default is no username (open server)) ;password=123 ; (default is no password (open server)) [supervisorctl] ... ;serverurl=http://127.0.0.1:9001 ; use an http:// url to specify an inet socket ;username=chris ; should be same as http_username if set ;password=123 ; should be same as http_password if set |
使用 include
在配置文件的最后,有一个 [include] 的配置项,跟 Nginx 一样,可以 include 某个文件夹下的所有配置文件,这样我们就可以为每个进程或相关的几个进程的配置单独写成一个文件。
1 2 |
[include] files = /etc/supervisord.d/*.ini |
进程的配置样例
一个简单的例子如下
1 2 3 4 5 6 7 8 9 10 11 12 |
; 设置进程的名称,使用 supervisorctl 来管理进程时需要使用该进程名 [program:your_program_name] command=python server.py --port=9000 ;numprocs=1 ; 默认为1 ;process_name=%(program_name)s ; 默认为 %(program_name)s,即 [program:x] 中的 x directory=/home/python/tornado_server ; 执行 command 之前,先切换到工作目录 user=oxygen ; 使用 oxygen 用户来启动该进程 ; 程序崩溃时自动重启,重启次数是有限制的,默认为3次 autorestart=true redirect_stderr=true ; 重定向输出的日志 stdout_logfile = /var/log/supervisord/tornado_server.log loglevel=info |
设置日志级别
loglevel
指定了日志的级别,用 Python 的 print 语句输出的日志是不会被记录到日志文件中的,需要搭配 Python 的 logging 模块来输出有指定级别的日志。
多个进程
按照官方文档的定义,一个 [program:x] 实际上是表示一组相同特征或同类的进程组,也就是说一个 [program:x] 可以启动多个进程
。这组进程的成员是通过 numprocs
和 process_name
这两个参数来确定的,这句话什么意思呢,我们来看这个例子。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
; 设置进程的名称,使用 supervisorctl 来管理进程时需要使用该进程名 [program:foo] ; 可以在 command 这里用 python 表达式传递不同的参数给每个进程 command=python server.py --port=90%(process_num)02d directory=/home/python/tornado_server ; 执行 command 之前,先切换到工作目录 ; 若 numprocs 不为1,process_name 的表达式中一定要包含 process_num 来区分不同的进程 numprocs=2 process_name=%(program_name)s_%(process_num)02d; user=oxygen ; 使用 oxygen 用户来启动该进程 autorestart=true ; 程序崩溃时自动重启 redirect_stderr=true ; 重定向输出的日志 stdout_logfile = /var/log/supervisord/tornado_server.log loglevel=info |
上面这个例子会启动两个进程,process_name 分别为 foo:foo_01
和 foo:foo_02
。通过这样一种方式,就可以用一个 [program:x] 配置项,来启动一组非常类似的进程。
再介绍两个配置项 stopasgroup
和 killasgroup
1 2 3 4 5 |
; 默认为 false,如果设置为 true,当进程收到 stop 信号时,会自动将该信号发给该进程的子进程。如果这个配置项为 true,那么也隐含 killasgroup 为 true。例如在 Debug 模式使用 Flask 时,Flask 不会将接收到的 stop 信号也传递给它的子进程,因此就需要设置这个配置项。 stopasgroup=false ; send stop signal to the UNIX process ; 默认为 false,如果设置为 true,当进程收到 kill 信号时,会自动将该信号发给该进程的子进程。如果这个程序使用了 python 的 multiprocessing 时,就能自动停止它的子线程。 killasgroup=false ; SIGKILL the UNIX process group (def false) |
更详细的配置例子,可以参考如下,官方文档在这里
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 |
;[program:theprogramname] ;command=/bin/cat ; the program (relative uses PATH, can take args) ;process_name=%(program_name)s ; process_name expr (default %(program_name)s) ;numprocs=1 ; number of processes copies to start (def 1) ;directory=/tmp ; directory to cwd to before exec (def no cwd) ;umask=022 ; umask for process (default None) ;priority=999 ; the relative start priority (default 999) ;autostart=true ; start at supervisord start (default: true) ;autorestart=unexpected ; whether/when to restart (default: unexpected) ;startsecs=1 ; number of secs prog must stay running (def. 1) ;startretries=3 ; max # of serial start failures (default 3) ;exitcodes=0,2 ; ''expected'' exit codes for process (default 0,2) ;stopsignal=QUIT ; signal used to kill process (default TERM) ;stopwaitsecs=10 ; max num secs to wait b4 SIGKILL (default 10) ;stopasgroup=false ; send stop signal to the UNIX process group (default false) ;killasgroup=false ; SIGKILL the UNIX process group (def false) ;user=chrism ; setuid to this UNIX account to run the program ;redirect_stderr=true ; redirect proc stderr to stdout (default false) ;stdout_logfile=/a/path ; stdout log path, NONE for none; default AUTO ;stdout_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB) ;stdout_logfile_backups=10 ; # of stdout logfile backups (default 10) ;stdout_capture_maxbytes=1MB ; number of bytes in ''capturemode'' (default 0) ;stdout_events_enabled=false ; emit events on stdout writes (default false) ;stderr_logfile=/a/path ; stderr log path, NONE for none; default AUTO ;stderr_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB) ;stderr_logfile_backups=10 ; # of stderr logfile backups (default 10) ;stderr_capture_maxbytes=1MB ; number of bytes in ''capturemode'' (default 0) ;stderr_events_enabled=false ; emit events on stderr writes (default false) ;environment=A="1",B="2" ; process environment additions (def no adds) ;serverurl=AUTO ; override serverurl computation (childutils) |
将多个进程按组管理
Supervisor 同时还提供了另外一种进程组的管理方式,通过这种方式,可以使用 supervisorctl 命令来管理一组进程。跟 [program:x] 的进程组不同的是,这里的进程是一个个的 [program:x] 。
1 2 3 |
[group:thegroupname] programs=progname1,progname2 ; each refers to ''x'' in [program:x] definitions priority=999 ; the relative start priority (default 999) |
当添加了上述配置后,progname1
和 progname2
的进程名就会变成thegroupname:progname1
和 thegroupname:progname2
以后就要用这个名字来管理进程了,而不是之前的 progname1
。
以后执行 supervisorctl stop thegroupname:
就能同时结束 progname1
和 progname2
,执行 supervisorctl stop thegroupname:progname1
就能结束 progname1
。supervisorctl 的命令我们稍后介绍。
启动 supervisord
执行 supervisord 命令,将会启动 supervisord 进程,同时我们在配置文件中设置的进程也会相应启动。
1 2 3 4 5 6 |
# 使用默认的配置文件 /etc/supervisord.conf supervisord # 明确指定配置文件 supervisord -c /etc/supervisord.conf # 使用 user 用户启动 supervisord supervisord -u user |
更多参数请参考文档
supervisorctl 命令介绍
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# 停止某一个进程,program_name 为 [program:x] 里的 x supervisorctl stop program_name # 启动某个进程 supervisorctl start program_name # 重启某个进程 supervisorctl restart program_name # 结束所有属于名为 groupworker 这个分组的进程 (start,restart 同理) supervisorctl stop groupworker: # 结束 groupworker:name1 这个进程 (start,restart 同理) supervisorctl stop groupworker:name1 # 停止全部进程,注:start、restart、stop 都不会载入最新的配置文件 supervisorctl stop all # 载入最新的配置文件,停止原有进程并按新的配置启动、管理所有进程 supervisorctl reload # 根据最新的配置文件,启动新配置或有改动的进程,配置没有改动的进程不会受影响而重启 supervisorctl update |
注意:显示用 stop 停止掉的进程,用 reload 或者 update 都不会自动重启。也可以参考这里
开机自动启动 Supervisord
Supervisord 默认情况下并没有被安装成服务,它本身也是一个进程。官方已经给出了脚本可以将 Supervisord 安装成服务,可以参考这里查看各种操作系统的安装脚本,但是我用官方这里给的 Ubuntu 脚本却无法运行。
安装方法可以参考 serverfault 上的回答。
比如我是 Ubuntu 系统,可以这么安装,这里选择了另外一个脚本
1 2 3 4 5 6 7 8 9 |
# 下载脚本 sudo su - root -c "sudo curl https://gist.githubusercontent.com/howthebodyworks/176149/raw/d60b505a585dda836fadecca8f6b03884153196b/supervisord.sh > /etc/init.d/supervisord" # 设置该脚本为可以执行 sudo chmod +x /etc/init.d/supervisord # 设置为开机自动运行 sudo update-rc.d supervisord defaults # 试一下,是否工作正常 service supervisord stop service supervisord start |
注意:这个脚本下载下来后,还需检查一下与我们的配置是否相符合,比如默认的配置文件路径,pid 文件路径等,如果存在不同则需要进行一些修改。
其实还有一个简单的方法,因为 Linux 在启动的时候会执行 /etc/rc.local
里面的脚本,所以只要在这里添加执行命令就可以
1 2 |
# 如果是 Ubuntu 添加以下内容 /usr/local/bin/supervisord -c /etc/supervisord.conf |
1 2 |
# 如果是 Centos 添加以下内容
/usr/bin/supervisord -c /etc/supervisord.conf |
以上内容需要添加在 exit 命令前,而且由于在执行 rc.local 脚本时,PATH 环境变量未全部初始化,因此命令需要使用绝对路径。
在添加前,先在终端测试一下命令是否能正常执行,如果找不到 supervisord,可以用如下命令找到
sudo find / -name supervisord
Python-Python的super()如何处理多重继承?
我在使用Python进行面向对象的编程方面非常陌生,并且在理解super()
函数(新样式类)时遇到困难,特别是在涉及多重继承时。
例如,如果你有类似的东西:
class First(object): def __init__(self): print "first"class Second(object): def __init__(self): print "second"class Third(First, Second): def __init__(self): super(Third, self).__init__() print "that''s it"
我不明白的是:Third()
该类会继承两个构造函数方法吗?如果是,那么哪个将与super()
一起运行,为什么?
而如果要运行另一个呢?我知道这与Python方法解析顺序(MRO)
有关。
答案1
小编典典Guido自己在他的博客文章Method Resolution Order
(包括两次较早的尝试)中对此进行了合理的详细说明。
在你的示例中,Third()将调用First.__init__
。Python从左到右列出,在类的父级中查找每个属性。在这种情况下,我们正在寻找__init__
。所以,如果你定义
class Third(First, Second): ...
Python将首先查看First,如果First没有该属性,则它将查看Second。
当继承开始跨越路径时(例如,如果First继承自Second),这种情况会变得更加复杂。阅读上面的链接以获取更多详细信息,但是简而言之,Python将尝试维护每个类从子类本身开始在继承列表上出现的顺序。
因此,例如,如果你有:
class First(object): def __init__(self): print "first"class Second(First): def __init__(self): print "second"class Third(First): def __init__(self): print "third"class Fourth(Second, Third): def __init__(self): super(Fourth, self).__init__() print "that''s it"MRO将是 [Fourth, Second, Third, First].
顺便说一句:如果Python无法找到一致的方法解析顺序,它将引发异常,而不是退回到可能使用户感到惊讶的行为。
编辑以添加一个模棱两可的MRO的示例:
class First(object): def __init__(self): print "first"class Second(First): def __init__(self): print "second"class Third(First, Second): def __init__(self): print "third"
是否应Third的MRO是[First, Second]
或[Second, First]
?没有明显的期望,Python会引发错误:
TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution order (MRO) for bases Second, First
编辑:我看到几个人争辩说上面的示例缺少super()
调用,所以让我解释一下:这些示例的重点是说明MRO的构造方式。它们不打算打印“第一\第二\第三”或其他内容。你可以并且应该当然使用该示例,添加super()
调用,看看会发生什么,并且对Python的继承模型有更深入的了解。但我的目标是保持简单,并说明MRO的构建方式。正如我所解释的那样:
>>> Fourth.__mro__(<class ''__main__.Fourth''>, <class ''__main__.Second''>, <class ''__main__.Third''>, <class ''__main__.First''>, <type ''object''>)
Python3中的super()函数详解
关于Python3中的super()函数
我们都知道,在Python3中子类在继承父类的时候,当子类中的方法与父类中的方法重名时,子类中的方法会覆盖父类中的方法,
那么,如果我们想实现同时调用父类和子类中的同名方法,就需要使用到super()这个函数,用法为super().函数名()
下面是一个例子:
class A1():
def go(self):
print("go A1 go")
class A2():
def go(self):
print("go A2 go")
class A3():
def go(self):
print("go A3 go")
class C(A3):
pass
class B(A1,A2):
pass
class D(B,C):
def go(self):
print("NMSL")
super().go()
d1 = D()
d1.go()
print(D.__mro__)
输出结果为:
NMSL
go A1 go
(<class ''__main__.D''>, <class ''__main__.B''>, <class ''__main__.A1''>, <class ''__main__.A2''>, <class ''__main__.C''>, <class ''__main__.A3''>, <class ''object''>)
这里的__mro__属性显示了当类调用方法时,如果父类和子类中有同名方法情况下的查找顺序。
如图,当我们实例化D类并调用类中的go方法时,go方法中有一条语句调用了父类的go方法,__mro__属性显示了如何查找这个方法(当然,自身类中的go方法不算),最后我们知道它调用的是A1类中的go方法,那么有些人会疑惑,为什么它不调用更近的的A3类或者A2类中go方法呢,这就要涉及到super()函数实现顺序查找的算法,这个算法即为C3算法。我的另一篇博客中记录了这个算法的原理。
假如D类中本身就没有go方法,那么我们再使用super()函数进行调用go方法,它会选择哪一个父类的呢?
代码如下:
class A1():
def go(self):
print("go A1 go")
class A2():
def go(self):
print("go A2 go")
class A3():
def go(self):
print("go A3 go")
class C(A3):
pass
class B(A1,A2):
pass
class D(B,C):
def gogo(self):
print("NMSL")
super().go()
d1 = D()
d1.gogo()
print(D.__mro__)
运行后输出结果:
NMSL
go A1 go
(<class ''__main__.D''>, <class ''__main__.B''>, <class ''__main__.A1''>, <class ''__main__.A2''>, <class ''__main__.C''>, <class ''__main__.A3''>, <class ''object''>)
可以看到结果还是这样。
如果D类中不定义方法,仅仅在类的外部通过实例调用go方法,查找过程也是一样的。
如图:
class D(B,C):
pass
d1 = D()
d1.go()
print(D.__mro__)
结果:
NMSL
go A1 go
(<class ''__main__.D''>, <class ''__main__.B''>, <class ''__main__.A1''>, <class ''__main__.A2''>, <class ''__main__.C''>, <class ''__main__.A3''>, <class ''object''>)
以上就是对于super()函数的个人看法。
python3的super详解
说到 super, 大家可能觉得很简单呀,不就是用来调用父类方法的嘛。如果真的这么简单的话也就不会有这篇文章了,且听我细细道来。
约定
在开始之前我们来约定一下本文所使用的 Python 版本。默认用的是 Python 3,也就是说:本文所定义的类都是新式类。如果你用到是 Python 2 的话,记得继承 object:
# 默认, Python 3
class A: pass # Python 2 class A(object): pass
Python 3 和 Python 2 的另一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx :
# 默认,Python 3
class B(A): def add(self, x): super().add(x) # Python 2 class B(A): def add(self, x): super(B, self).add(x)
所以,你如果用的是 Python 2 的话,记得将本文的 super() 替换为 suepr(Class, self) 。
如果还有其他不兼容 Python 2 的情况,我会在文中注明的。
单继承
在单继承中 super 就像大家所想的那样,主要是用来调用父类的方法的。
class A:
def __init__(self): self.n = 2 def add(self, m): print(''self is {0} @A.add''.format(self)) self.n += m class B(A): def __init__(self): self.n = 3 def add(self, m): print(''self is {0} @B.add''.format(self)) super().add(m) self.n += 3
你觉得执行下面代码后, b.n 的值是多少呢?
b = B() b.add(2) print(b.n)
执行结果如下:
self is <__main__.B object at 0x106c49b38> @B.add self is <__main__.B object at 0x106c49b38> @A.add 8
这个结果说明了两个问题:
- 1、super().add(m) 确实调用了父类 A 的 add 方法。
- 2、super().add(m) 调用父类方法 def add(self, m) 时, 此时父类中 self 并不是父类的实例而是子类的实例, 所以 b.add(2) 之后的结果是 5 而不是 4 。
不知道这个结果是否和你想到一样呢?下面我们来看一个多继承的例子。
多继承
这次我们再定义一个 class C,一个 class D:
class C(A): def __init__(self): self.n = 4 def add(self, m): print(''self is {0} @C.add''.format(self)) super().add(m) self.n += 4 class D(B, C): def __init__(self): self.n = 5 def add(self, m): print(''self is {0} @D.add''.format(self)) super().add(m) self.n += 5
下面的代码又输出啥呢?
d = D() d.add(2) print(d.n)
这次的输出如下:
self is <__main__.D object at 0x10ce10e48> @D.add self is <__main__.D object at 0x10ce10e48> @B.add self is <__main__.D object at 0x10ce10e48> @C.add self is <__main__.D object at 0x10ce10e48> @A.add 19
你说对了吗?你可能会认为上面代码的输出类似:
self is <__main__.D object at 0x10ce10e48> @D.add self is <__main__.D object at 0x10ce10e48> @B.add self is <__main__.D object at 0x10ce10e48> @A.add 15
为什么会跟预期的不一样呢?下面我们将一起来看看 super 的奥秘。
super 是个类
当我们调用 super() 的时候,实际上是实例化了一个 super 类。你没看错, super 是个类,既不是关键字也不是函数等其他数据结构:
>>> class A: pass ... >>> s = super(A) >>> type(s) <class ''super''> >>>
在大多数情况下, super 包含了两个非常重要的信息: 一个 MRO 以及 MRO 中的一个类。当以如下方式调用 super 时:
super(a_type, obj)
MRO 指的是 type(obj) 的 MRO, MRO 中的那个类就是 a_type , 同时 isinstance(obj, a_type) == True 。
当这样调用时:
super(type1, type2)
MRO 指的是 type2 的 MRO, MRO 中的那个类就是 type1 ,同时 issubclass(type2, type1) == True 。
那么, super() 实际上做了啥呢?简单来说就是:提供一个 MRO 以及一个 MRO 中的类 C , super() 将返回一个从 MRO 中 C 之后的类中查找方法的对象。
也就是说,查找方式时不是像常规方法一样从所有的 MRO 类中查找,而是从 MRO 的 tail 中查找。
举个例子, 有个 MRO:
[A, B, C, D, E, object]
下面的调用:
super(C, A).foo()
super 只会从 C 之后查找,即: 只会在 D 或 E 或 object 中查找 foo 方法。
多继承中 super 的工作方式
再回到前面的
d = D() d.add(2) print(d.n)
现在你可能已经有点眉目,为什么输出会是
self is <__main__.D object at 0x10ce10e48> @D.add self is <__main__.D object at 0x10ce10e48> @B.add self is <__main__.D object at 0x10ce10e48> @C.add self is <__main__.D object at 0x10ce10e48> @A.add 19
了吧 ;)
下面我们来具体分析一下:
-
D 的 MRO 是: [D, B, C, A, object] 。 备注: 可以通过 D.mro() (Python 2 使用 D.__mro__ ) 来查看 D 的 MRO 信息)
-
详细的代码分析如下:
class A: def __init__(self): self.n = 2 def add(self, m): # 第四步 # 来自 D.add 中的 super # self == d, self.n == d.n == 5 print(''self is {0} @A.add''.format(self)) self.n += m # d.n == 7 class B(A): def __init__(self): self.n = 3 def add(self, m): # 第二步 # 来自 D.add 中的 super # self == d, self.n == d.n == 5 print(''self is {0} @B.add''.format(self)) # 等价于 suepr(B, self).add(m) # self 的 MRO 是 [D, B, C, A, object] # 从 B 之后的 [C, A, object] 中查找 add 方法 super().add(m) # 第六步 # d.n = 11 self.n += 3 # d.n = 14 class C(A): def __init__(self): self.n = 4 def add(self, m): # 第三步 # 来自 B.add 中的 super # self == d, self.n == d.n == 5 print(''self is {0} @C.add''.format(self)) # 等价于 suepr(C, self).add(m) # self 的 MRO 是 [D, B, C, A, object] # 从 C 之后的 [A, object] 中查找 add 方法 super().add(m) # 第五步 # d.n = 7 self.n += 4 # d.n = 11 class D(B, C): def __init__(self): self.n = 5 def add(self, m): # 第一步 print(''self is {0} @D.add''.format(self)) # 等价于 super(D, self).add(m) # self 的 MRO 是 [D, B, C, A, object] # 从 D 之后的 [B, C, A, object] 中查找 add 方法 super().add(m) # 第七步 # d.n = 14 self.n += 5