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
嗯....我认为,hasattr
和callable
将完成同样的目标,最简单的方法:
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中的变量参数函数和方法,似乎知道函数的"必需"参数数量的价值非常小(从程序/内省的角度来看).
有方法:
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可以是几乎任何东西.