请考虑以下代码:
args, varargs, varkw, defaults = inspect.getargspec(method)
if inspect.ismethod(method):
args = args[1:] # Skip 'self'
Run Code Online (Sandbox Code Playgroud)
在Python 2上运行此操作并在self中添加内容时,将跳过self(如注释中所述).在Python 3上,我在使用代码时遇到了麻烦Class.method(即没有instance.method).问题类似于在Python 3中检测类(非实例)中的绑定方法,但没有解决方法.使用inspect.isroutine()或 inspect.isfunction()破坏非方法的代码(没有自我).使用hasattr(method, '__self__')不起作用Class.method.
我为此编写了一个小测试文件:
from __future__ import print_function
import inspect
def args_without_self(method):
args, varargs, varkw, defaults = inspect.getargspec(method)
if inspect.ismethod(method):
args = args[1:] # Skip 'self'
return args
class Class(object):
def method(self, a, b, c):
pass
@staticmethod
def static(a, b, c):
pass
@classmethod
def classmethod(cls, …Run Code Online (Sandbox Code Playgroud)