有没有Python相当于Ruby的respond_to?

时间:2011-05-22 08:22:49

标签: python ruby class

是否可以查看某个类是否响应Python中的方法?比如红宝石:

class Fun
  def hello
    puts 'Hello'
  end
end

fun = Fun.new
puts fun.respond_to? 'hello' # true

还有办法查看该方法需要多少个参数吗?

4 个答案:

答案 0 :(得分:17)

嗯......我认为hasattrcallable是实现同一目标的最简单方法:

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

hasattr(Fun, 'hello')   # -> True
callable(Fun.hello)     # -> True

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

try:
    callable(Fun.goodbye)
except AttributeError, e:
    return False

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

答案 1 :(得分:8)

有方法:

func = getattr(Fun, "hello", None)
if callable(func):
  ...

元数:

import inspect
args, varargs, varkw, defaults = inspect.getargspec(Fun.hello)
arity = len(args)

请注意,如果varargs和/或varkw不是无,则arity几乎可以是任何内容。

答案 2 :(得分:2)

dir(instance)返回对象属性列表 getattr(instance,"attr")返回对象的属性 如果x可以调用,则callable(x)返回True。

class Fun(object):
    def hello(self):
        print "Hello"

f = Fun()
callable(getattr(f,'hello'))

答案 3 :(得分:1)

我不是Ruby专家,所以我不确定这是否能回答你的问题。我想你想检查一个对象是否包含一个方法。有很多方法可以做到这一点。您可以尝试使用hasattr()函数,查看对象是否具有该方法:

hasattr(fun, "hello") #True

或者你可以按照python指南不要问,只要问这样,只要抓住当对象没有方法时抛出的异常:

try:
    fun.hello2()
except AttributeError:
    print("fun does not have the attribute hello2")
相关问题