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

标签 python python-3.x methods self

考虑以下代码:

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/

相关文章:

python - 根据条件排列旗帜中的条纹

python-3.x - Ubuntu 中的 Azure Pipeline 部署到 Debian 中的 Azure 应用服务

python - 在读取实际行之前,如何自动解析打开的audit.log 文件的语法?

Python 通过不同路径导入相同对象 - 类属性和基元之间的不同行为

python - 在 Python 3 中获取未绑定(bind)方法对象的定义类

java - java 8中的方法引用?

php - `return;` 和不返回有什么区别?

Java方法和调用方法太多次

python - 使用 rebuild_index 的 Django Haystack 和 Elasticsearch 错误

python - 有没有办法让 numpy 数组中的数字随机为正或负?