小编hro*_*cok的帖子

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

请考虑以下代码:

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)

python methods self python-3.x

3
推荐指数
1
解决办法
922
查看次数

标签 统计

methods ×1

python ×1

python-3.x ×1

self ×1