Python设置docstring并获取动态生成的classmethod的方法名称

时间:2014-10-01 15:35:49

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

我试图获取/设置动态创建的类方法的名称和文档字符串,如下所示,但我很难弄清楚如何做到这一点:

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'),如果我很难-code' test.myF1'而不是' test.func'我得到了' instancemethod'的属性'__doc__'的AttributeError。不可写。

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

1 个答案:

答案 0 :(得分: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'}