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

Python设置docstring并获取动态生成的classmethod的方法名,python,decorator,class-method,python-decorators,docstring,Python,Decorator,Class Method,Python Decorators,Docstring,我正在尝试按如下方式获取/设置动态创建的类方法的名称和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 = ['

我正在尝试按如下方式获取/设置动态创建的类方法的名称和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,“\uu doc\uuuu”,“对%s”%func)
,这导致了AttributeError异常(类型对象“test”没有属性“func”),如果我硬编码'test.myF1'而不是'test.func',我会为'instancemethod'的属性
“\uuuu doc\uuuuuu”
获取一个不可写的AttributeError


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

您的泛型函数本身没有docstring。当我添加docstring时,这对我来说很好:

    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,但该docstring对于myF1、myF2和我添加到函数列表中的任何其他函数都是静态的/相同的。我希望docstring是动态的,并包含函数名。sys.exit()是不必要的,只是一种习惯。这样做是不够的:打印“docstring:”,x.myF1.\uuu name\uuu+x.myF1.\uu doc\uuuu
x.myF1.\uuu name\uuu
返回“genericFunc”,而不是“myF1”或“myF2”。我需要能够从generalFunc中获取该值。