gpt4 book ai didi

python - 列出函数/方法的参数并在 Python 3 中跳过 'self'

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:37 25 4
gpt4 key购买 nike

考虑以下代码:

args, varargs, varkw, defaults = inspect.getargspec(method)
if inspect.ismethod(method):
args = args[1:] # Skip 'self'

在 Python 2 上运行它并使用 self 添加内容时,self 被跳过(如评论中所述)。然而,在 Python 3 上,我在使用 Class.method 上的代码时遇到了麻烦(即不是 instance.method)。问题类似于Detecting bound method in classes (not instances) in Python 3 ,但没有一个答案有效。使用 inspect.isroutine()inspect.isfunction() 会破坏非方法(无 self )的代码。使用 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))

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

最佳答案

在 Python 3 上,您无法检测类中的方法,因为它们从未绑定(bind)。它们只是常规函数

顶多看看他们的qualified name猜测它们是否可能是方法,然后查看第一个参数是否命名为self。启发式和猜测,换句话说:

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

关于python - 列出函数/方法的参数并在 Python 3 中跳过 'self',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27777939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com