我想找出Python中方法的优点(它接收的参数数量).现在我这样做:
def arity(obj, method):
return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
class Foo:
def bar(self, bla):
pass
arity(Foo(), "bar") # => 1
Run Code Online (Sandbox Code Playgroud)
我希望能够做到这一点:
Foo().bar.arity() # => 1
Run Code Online (Sandbox Code Playgroud)
更新:现在上面的函数失败了内置类型,对此的任何帮助也将受到赞赏:
# Traceback (most recent call last):
# File "bla.py", line 10, in <module>
# print arity('foo', 'split') # =>
# File "bla.py", line 3, in arity
# return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
# AttributeError: 'method_descriptor' object has no attribute 'func_co
Run Code Online (Sandbox Code Playgroud) 可能重复:
如何在Python中找出方法的arity
给定一个python函数,我如何以编程方式确定它所需的参数数量?