這兩個是python中的可變參數。*args表示任何多個無名參數,它是一個tuple(元祖);**kwargs表示關鍵字參數,它是一個dict(字典)。
並且同時使用*args和**kwargs時,必須*args參數列要在**kwargs前。看下面例子:
# https://godjango.com/105-understanding-args-and-kwargs/(例子來源)
1 def print_args(d1, d2, d3): 2 print(d1, d2, d3) 3 4 data = ('foo', 'bar', 'baz') 5 print_args(*data) # 在data之前使用一個星號,表示讓函數接受任意多的位置參數。 6 >>> foo bar baz 7 8 def print_args(*args): 9 for arg in args: 10 print(arg) 11 print_args(1, 2, 3) 12 >>> 1 13 >>> 2 14 >>> 3 15 16 def print_args(*args): 17 print(args) 18 print_args(1, 2, 3) 19 >>> (1, 2, 3) 20 21 def print_args(a, b, c, *args): 22 print(a, b, c, args) 23 print_args(1, 2, 3, 4, 5) 24 >>> 1 2 3 (4, 5) 25 26 27 def print_kwargs(**kwargs): # 在參數名之前使用2個星號來支持任意多的關鍵字參數 28 print(kwargs) 29 print_kwargs(foo='bar', hello='world') 30 >>> {'foo': 'bar', 'hello': 'world'} 31 32 def print_kwargs(latitude=None, longitude=None): 33 print(latitude, longitude) 34 35 data = {'latitude': 0.00, 'longitude': 1.00} 36 print_data(**data) 37 >>> 0.00 1.00 38 39 def print_kwargs(lat=None, long=None, **kwargs): 40 print(lat, long, kwargs) 41 print_kwargs(1, 2, data='other') 42 >>> 1 2 {'data': 'other'} 43
Python super()函數用法
super() 函數是用於調用父類(超類)的一個方法。好處是可以避免直接調用父類的名字
值得注意的是,在python3中直接使用 super().xxx 代替 super(Class, self).xxx (Python2格式)
# http://www.runoob.com/python/python-func-super.html(例子來源)
1 class FooParent(object): 2 def __init__(self): 3 self.parent = 'I\'m the parent.' 4 print ('Parent') 5 6 def bar(self,message): 7 print ("%s from Parent" % message) 8 9 class FooChild(FooParent): 10 def __init__(self): 11 # super(FooChild,self) 首先找到 FooChild 的父類(就是類 FooParent),然后把類B的對象 FooChild 轉換為類 FooParent 的對象 12 super(FooChild,self).__init__() 13 print ('Child') 14 15 def bar(self,message): 16 super(FooChild, self).bar(message) 17 print ('Child bar fuction') 18 print (self.parent) 19 20 if __name__ == '__main__': 21 fooChild = FooChild() 22 fooChild.bar('HelloWorld')
輸出為:
1 Parent 2 Child 3 HelloWorld from Parent 4 Child bar fuction 5 I'm the parent.