據help(getattr)
,兩個或三個參數被接受:是否可以編寫一個像getattr()那樣工作的函數簽名?
getattr(...)
getattr(object, name[, default]) -> value
做一些簡單的測試,我們可以證實這一點:
>>> obj = {}
>>> getattr(obj, 'get')
<built-in method get of dict object at 0x7f6d4beaf168>
>>> getattr(obj, 'bad', 'with default')
'with default'
太少/太多的爭論也像預期的那樣:
>>> getattr()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: getattr expected at least 2 arguments, got 0
>>> getattr(obj, 'get', 'with default', 'extra')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: getattr expected at most 3 arguments, got 4
幫助文本中指定的參數名似乎不被接受爲關鍵字參數:
>>> getattr(object=obj, name='get')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: getattr() takes no keyword arguments
的inspect
模塊是沒有幫助在這裏:
>>> import inspect
>>> inspect.getargspec(getattr)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/inspect.py", line 816, in getargspec
raise TypeError('{!r} is not a Python function'.format(func))
TypeError: <built-in function getattr> is not a Python function
(messaging is a little different in python3, but the gist is the same)
現在的問題是:是否有寫我自己的Python功能與行爲完全像getattr
的簽名的簽名一個簡單的方法?也就是說,關鍵字參數是不允許的,並且最小數量/最大數量的參數被執行?我來最接近的是以下幾點:
def myfunc(*args):
len_args = len(args)
if len_args < 2:
raise TypeError('expected at least 2 arguments, got %d' % len_args)
elif len_args > 3:
raise TypeError('expected at most 3 arguments, got %d' % len_args)
...
但現在,而不是像object
和name
有意義的參數名稱,我們得到args[0]
和args[1]
。這也是很多的樣板,感覺很不愉快。我知道,作爲內置的,getattr
必須與典型的Python代碼有很大的不同,並且可能沒有辦法完美地模擬它的行爲方式。但這是我一段時間以來的好奇心。
@Makoto:不重複;可選參數很容易,但是這個問題特別針對僅限位置的參數行爲。 – user2357112