Python中是否有类似Ruby中respond_to的功能?

11 投票
4 回答
4621 浏览
提问于 2025-04-16 18:07

有没有办法查看一个类在Python中是否能使用某个方法?就像在Ruby里那样:

class Fun
  def hello
    puts 'Hello'
  end
end

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

还有没有办法查看这个方法需要多少个参数?

4 个回答

2

dir(instance) 会返回一个对象的属性列表。也就是说,它会告诉你这个对象有哪些可以使用的特性和功能。
getattr(instance,"attr") 会返回对象的某个特定属性。简单来说,就是你可以通过这个命令来获取对象里面的某个具体内容。
callable(x) 如果 x 是可以被调用的(比如函数),那么它会返回 True。也就是说,这个命令可以用来检查某个东西是不是可以像函数那样被执行。

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

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

有一个方法:

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

参数个数:

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

请注意,如果你使用了 varargs(可变参数)和/或 varkw(可变关键字参数),那么参数个数可以是非常灵活的。

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中定义可选参数、默认参数和可变参数函数是多么简单,知道一个函数“需要”的参数数量从编程和检查的角度来看似乎并没有太大意义。

撰写回答