列出函数/方法的参数,并在Python 3中跳过"self"

hro*_*cok 3 python methods self python-3.x

请考虑以下代码:

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, a, b, c):
        pass


def function(a, b, c):
    pass

instance = Class()

print(args_without_self(Class.method))
print(args_without_self(instance.method))
print(args_without_self(Class.static))
print(args_without_self(instance.static))
print(args_without_self(Class.classmethod))
print(args_without_self(instance.classmethod))
print(args_without_self(function))
Run Code Online (Sandbox Code Playgroud)

该代码适用于Python 2和3.但是在Python 3中args_without_self(Class.method)也有自我(我想避免这种情况,但不要破坏其他代码).Everythign应该打印['a', 'b', 'c'].

Mar*_*ers 7

在Python 3上,你不能检测类的方法,因为它们永远不会被绑定.它们只是常规功能.

最多可以查看他们的限定名称猜测它们是否可能是方法,然后查看第一个参数是否已命名self.启发式和猜测,换句话说:

if inspect.isfunction(method) and `.` in method.__qualname__ and args[0] == 'self':
    args = args[1:]    # Skip 'self'
Run Code Online (Sandbox Code Playgroud)