相关疑难解决方法(0)

如何在Python中找出方法的arity

我想找出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 metaprogramming

30
推荐指数
2
解决办法
7554
查看次数

Python函数参数计数

可能重复:
如何在Python中找出方法的arity

给定一个python函数,我如何以编程方式确定它所需的参数数量?

python metaprogramming

2
推荐指数
1
解决办法
3889
查看次数

标签 统计

metaprogramming ×2

python ×2