阅读源码经常看到以**kwargs进行传递, 却不知道人家为什么要这样写.
比如说Tornado源码,位置在: websocket.py文件 -> WebSocketHandler类 -> send_error方法中,就采用了 **kwargs.
class WebSocketHandler(tornado.web.RequestHandler):
......
......
......
def send_error(self, *args, **kwargs):
if self.stream is None:
super(WebSocketHandler, self).send_error(*args, **kwargs)
else:
# If we get an uncaught exception during the handshake,
# we have no choice but to abruptly close the connection.
# TODO: for uncaught exceptions after the handshake,
# we can close the connection more gracefully.
self.stream.close()
通过super的方式,直接调用父类tornado.web.RequestHandler的send_error方法, 接下来省略5000字。。。。
来模拟一下这种写法,如果在调用父类时,不传这个**kwargs,看看会发生什么情况。
python 2.7
# -.- coding:utf-8 -.-
# __author__ = 'zhengtong'
class People(object):
def __init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
class Friend(People):
def __init__(self, phone, **kwargs):
super(Friend, self).__init__(**kwargs)
self.phone = phone
def show(self):
return self.phone, self.age, self.name, self.sex
if __name__ == '__main__':
s = Friend('12345678911')
print(s.show())
# 运行结果
C:\Python27\python.exe C:/Users/zt/PycharmProjects/multi_super.py
Traceback (most recent call last):
File "C:/Users/zt/PycharmProjects/multi_super.py", line 21, in <module>
s = Friend('12345678911')
File "C:/Users/zt/PycharmProjects/multi_super.py", line 14, in __init__
super(Friend, self).__init__(**kwargs)
TypeError: __init__() takes exactly 4 arguments (1 given)
Process finished with exit code 1
python 3.5
# -.- coding:utf-8 -.-
# __author__ = 'zhengtong'
class People(object):
def __init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
class Friend(People):
def __init__(self, phone, **kwargs):
super(Friend, self).__init__(**kwargs)
self.phone = phone
def show(self):
return self.phone, self.age, self.name, self.sex
if __name__ == '__main__':
s = Friend('12345678911')
print(s.show())
#运行结果
C:\Python35-32\python.exe C:/Users/zt/PycharmProjects/multi_super2.py
Traceback (most recent call last):
File "C:/Users/zt/PycharmProjects/multi_super2.py", line 21, in <module>
s = Friend('12345678911')
File "C:/Users/zt/PycharmProjects/multi_super2.py", line 14, in __init__
super(Friend, self).__init__(**kwargs)
TypeError: __init__() missing 3 required positional arguments: 'name', 'sex', and 'age'
Process finished with exit code 1
两份几乎一样的代码,抛出来的异常缺不一样,python3清晰明了的告诉你为什么报了这个错误.
利用这种方式的好处是,透明传输(不需要关系传递过程中出现偏差),报错也是由被调用的函数抛出错误.
缺点是新手看不懂这是做什么用的,为什么这样做。
参考:
书籍: <python 3 面向对象编程>