變量傳遞**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 面向對象編程>

相關文章
相關標籤/搜索