【问题标题】:Python set docstring and get method name of dynamically generated classmethodPython 设置文档字符串并获取动态生成的类方法的方法名
【发布时间】:2014-11-26 12:18:15
【问题描述】:

我正在尝试获取/设置动态创建的类方法的名称和文档字符串,如下所示,但在弄清楚具体如何操作时遇到了麻烦:

import sys
import inspect

class test(object):
    pass

@classmethod
def genericFunc(cls, **kwargs):
    print "function:", (inspect.stack()[0][3])
    print "kwargs:", kwargs

function_list = ['myF1', 'myF2']
for func in function_list:
    setattr(test, func, genericFunc)
    #set docstring for func here?

if __name__ == '__main__':
    x = test()
    print "docstring:", x.myF1.__doc__
    x.myF1(arg1="foo")
    y = test()
    print "docstring:", y.myF2.__doc__
    y.myF2(arg1="foo", arg2="bar")
    sys.exit()

目前的输出是:

docstring: None
function: genericFunc
kwargs: {'arg1': 'foo'}
docstring: None
function: genericFunc
kwargs: {'arg1': 'foo', 'arg2': 'bar'}

我想要的是:

docstring: description of myF1
function: myF1
kwargs: {'arg1': 'foo'}
docstring: description of myF2
function: myF2
kwargs: {'arg1': 'foo', 'arg2': 'bar'}

在 for 循环中,我尝试执行 setattr(test.func, "__doc__", "description of %s" % func),这导致 AttributeError 异常(类型对象 'test' 没有属性 'func'),如果我硬编码 'test.myF1' 而不是 'test. func' 'instancemethod' 的属性 '__doc__' 的属性错误不可写。

最后,inspect.stack() 返回“genericFunc”而不是动态函数名(“myF1”或“myF2”),是否可以获取/设置后者,以便我可以检查方法的值__name__ 在 genericFunc 中根据其值执行某些操作?

【问题讨论】:

    标签: python decorator class-method python-decorators docstring


    【解决方案1】:

    您的通用函数本身没有文档字符串。当我添加一个文档字符串时,这对我来说很好:

        import inspect
    
        class test(object):
            pass
    
        @classmethod
        def genericFunc(cls, **kwargs):
            """ I'm a docstring"""
            print "function:", (inspect.stack()[0][3])
            print "kwargs:", kwargs
    
        function_list = ['myF1', 'myF2']
        for func in function_list:
            setattr(test, func, genericFunc)
            #set docstring for func here?
    
        if __name__ == '__main__':
            x = test()
            print "docstring:", x.myF1.__doc__
            x.myF1(arg1="foo")
            y = test()
            print "docstring:", y.myF2.__doc__
            y.myF2(arg1="foo", arg2="bar")
    

    另外,为什么 sys.exit() 最后?结果,我得到:

    docstring:  I'm a docstring
    function: genericFunc
    kwargs: {'arg1': 'foo'}
    docstring:  I'm a docstring
    function: genericFunc
    kwargs: {'arg1': 'foo', 'arg2': 'bar'}
    

    【讨论】:

    • corerct,但对于 myF1、myF2 和我添加到 function_list 的任何其他函数,该文档字符串将是静态的/相同的。我希望文档字符串是动态的并包含函数名称。 sys.exit() 是不必要的,只是一种习惯。
    • 这样的事情还不够吗: print "docstring:", x.myF1.__name__ + x.myF1.__doc__
    • x.myF1.__name__ 返回“genericFunc”,而不是“myF1”或“myF2”。而且我需要能够从 generalFunc 中获取该值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 2013-07-18
    • 2021-06-04
    • 2010-09-09
    • 2011-12-27
    • 2018-01-28
    相关资源
    最近更新 更多