我想找出 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
我希望能够做到这一点:
Foo().bar.arity() # => 1
更新:现在上述函数因内置类型而失败,对此的任何帮助也将不胜感激:
# 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