据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