变量传递**kwargs

阅读源码常常看到以**kwargs进行传递, 殊不知道人家为何要这样写.python

好比说Tornado源码,位置在: websocket.py文件 -> WebSocketHandler类 -> send_error方法中,就采用了 **kwargs.web

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,看看会发生什么状况。websocket

python 2.7socket

# -.- 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清晰明了的告诉你为何报了这个错误.tornado

 

 

利用这种方式的好处是,透明传输(不须要关系传递过程当中出现误差),报错也是由被调用的函数抛出错误.ui

缺点是新手看不懂这是作什么用的,为何这样作。code

 

参考:对象

    书籍: <python 3 面向对象编程>

相关文章
相关标签/搜索