【Python】Python小技巧:?args 和 kwargs 的樂趣
那么“args”和“kwargs”參數(shù)用來做什么呢?
In?[2]:?def?foo(required,?*args,?**kwargs):
???...:?????print(required)
???...:?????if?args:
???...:?????????print(args)
???...:?????if?kwargs:
???...:?????????print(kwargs)
In?[3]:?foo()
---------------------------------------------------------------------------
TypeError?????????????????????????????????Traceback?(most?recent?call?last)-3 -c19b6d9633cf>?in?
---->?1?foo()
TypeError:?foo()?missing?1?required?positional?argument:?'required'
In?[4]:?foo('hello')
hello
In?[5]:?foo('hello',?1,?2,?3)
hello
(1,?2,?3)
In?[6]:?foo('hello',?1,?2,?3,?key1='value',?key2=999)
hello
(1,?2,?3)
{'key1':?'value',?'key2':?999}
## 轉(zhuǎn)發(fā)可選或者關(guān)鍵字參數(shù)
In?[8]:?def?foo(x,?*args,?**kwargs):
???...:?????kwarg['name']?=?'Alice'
???...:?????new_args?=?args?+?('extra',?)
???...:?????bar(x,?*new_args,?**kwargs)
In?[9]:?class?Car:
???...:?????def?__init__(self,?color,?mileage):
???...:?????????self.color?=?color
???...:?????????self.mileage?=?mileage
???...:?
In?[10]:?class?AlwaysBlueCar(Car):
????...:?????def?__init__(self,?*args,?**kwargs):
????...:?????????super().__init__(*args,?**kwargs)
????...:?????????self.color?=?'blue'
In?[12]:?AlwaysBlueCar('green',?48392).color
Out[12]:?'blue'
import?functools
def?trace(f):
????...:[email protected](f)
????...:?????def?decorated_function(*args,?**kwargs):
????...:?????????print(f,?args,?kwargs)
????...:?????????result?=?f(*args,?**kwargs)
????...:?????????print(result)
????...:?????return?decorated_function
????
In?[11]:?@trace
????...:?def?greet(greeting,?name):
????...:?????return?'{},?{}!'.format(greeting,?name)
In?[14]:?greet('Hello',?'Bob') 0x7fefa69db700 >?('Hello',?'Bob')?{}
Hello,?Bob!
往期精彩回顧
評論
圖片
表情
