Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
列出函数/方法的参数并跳过';自我';在Python 3中_Python_Python 3.x_Methods_Self - Fatal编程技术网

列出函数/方法的参数并跳过';自我';在Python 3中

列出函数/方法的参数并跳过';自我';在Python 3中,python,python-3.x,methods,self,Python,Python 3.x,Methods,Self,考虑以下代码: args, varargs, varkw, defaults = inspect.getargspec(method) if inspect.ismethod(method): args = args[1:] # Skip 'self' 在Python2上运行此命令并使用self添加内容时,会跳过self(如注释中所述)。然而,在Python3上,我在Class.method(即不instance.method)上使用代码时遇到了麻烦。问题类似于,但没有一个答案是

考虑以下代码:

args, varargs, varkw, defaults = inspect.getargspec(method)
if inspect.ismethod(method):
    args = args[1:]    # Skip 'self'
在Python2上运行此命令并使用self添加内容时,会跳过self(如注释中所述)。然而,在Python3上,我在
Class.method
(即不
instance.method
)上使用代码时遇到了麻烦。问题类似于,但没有一个答案是有效的。使用
inspect.isroutine()
inspect.isfunction()
会中断非方法(无自身)的代码。使用
hasattr(方法''.\u 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))

该代码同时适用于Python2和Python3。然而,
args\u没有self(Class.method)
在Python3中也有self(我希望避免这种情况,但不要破坏其他情况)。EverythSign应该打印
['a','b','c']

在Python3上,您不能检测类上的方法,因为它们从不绑定。它们只是常规函数

您最多可以查看它们并猜测它们是否是方法,然后查看第一个参数是否命名为
self
。换句话说,启发式和猜测:

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

并希望没有人会给self起不同的名字:(@hroncok:或在嵌套函数中使用
self
,实际上它不是一个方法。但这就是限制。