有没有Python相当于Ruby的respond_to?

err*_*ler 11 ruby python class

是一种方法来查看一个类是否响应Python中的方法?喜欢红宝石:

class Fun
  def hello
    puts 'Hello'
  end
end

fun = Fun.new
puts fun.respond_to? 'hello' # true
Run Code Online (Sandbox Code Playgroud)

还有一种方法可以查看该方法需要多少个参数?

Jim*_*nis 17

嗯....我认为,hasattrcallable将完成同样的目标,最简单的方法:

class Fun:
    def hello(self):
        print 'Hello'

hasattr(Fun, 'hello')   # -> True
callable(Fun.hello)     # -> True
Run Code Online (Sandbox Code Playgroud)

当然,您可以callable(Fun.hello)在异常处理套件中调用:

try:
    callable(Fun.goodbye)
except AttributeError, e:
    return False
Run Code Online (Sandbox Code Playgroud)

至于所需参数数量的内省; 我认为这对语言来说具有可疑的价值(即使它存在于Python中),因为这不会告诉你所需的语义.鉴于可以轻松定义可选/缺省的参数以及Python中的变量参数函数和方法,似乎知道函数的"必需"参数数量的价值非常小(从程序/内省的角度来看).

  • yurib显示了一个使用getattr()和一个实例以及属性名称(作为字符串),然后在其上调用callable()的示例:callable(getattr(Fun(),'hello')) (2认同)
  • @error:`callable(getattr(Fun,"hello",None))`.如果对象没有所述属性,则`getattr`的第三个参数是默认值. (2认同)

log*_*og0 8

有方法:

func = getattr(Fun, "hello", None)
if callable(func):
  ...
Run Code Online (Sandbox Code Playgroud)

元数:

import inspect
args, varargs, varkw, defaults = inspect.getargspec(Fun.hello)
arity = len(args)
Run Code Online (Sandbox Code Playgroud)

请注意,如果您有varargs和/或varkw没有,则arity可以是几乎任何东西.