Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/maven/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以提取Python中类的所有方法吗?实例、类方法、静态方法_Python_Python 3.x - Fatal编程技术网

我可以提取Python中类的所有方法吗?实例、类方法、静态方法

我可以提取Python中类的所有方法吗?实例、类方法、静态方法,python,python-3.x,Python,Python 3.x,我执行了以下Python代码: class C: def m1(self): print('method m1') def m2(self): print('method m2') @classmethod def m3(cls): print('class method') @staticmethod def m4(): print('static method') print()

我执行了以下Python代码:

class C:
    def m1(self):
        print('method m1')
    def m2(self):
        print('method m2')
    @classmethod
    def m3(cls):
        print('class method')
    @staticmethod
    def m4():
        print('static method')

print()
for key, val in vars(C).items():
    print(key, '***', val, end=' ')
    if callable(val):
        print(True)
    else:
        print(False)
获得以下输出:

\uuuuuuuu模块\uuu***\ uuuuuu主\uuuuuuu错误
m1***正确
m2***正确
m3***错误
m4***错误
__口述错误
__weakref_uu***错误
__文件***无错误
我想知道为什么
callable
@classmethod
@staticmethod
返回
False

实际上,我试图找出一个类中所有方法的名称,这样我就可以用一个用户定义的装饰器来装饰该类的所有方法,而不是使用
dir(C)
getattr()

class C:
    def m1(self):
        print('method m1')

    def m2(self):
        print('method m2')

    @classmethod
    def m3(cls):
        print('class method')

    @staticmethod
    def m4():
        print('static method')


for val in dir(C):
    if callable(getattr(C, val)):
        print('***', val, end=' ')
        print(True)
    else:
        print(val, False)
输出:

vars()
,基本上是类块的
locals()
,返回作为普通函数转储的函数

m3 *** <classmethod object at 0x1089afbb0>
m4 *** <staticmethod object at 0x1089afcd0>

因为classmethod和staticmethod对象是不可调用的,除非通过访问器(访问器
getattr
调用,但
vars
不调用)对它们进行适当的包装。尝试
vars(C)['m3']()
,您将得到一个类型错误,因为它不可调用。因此,实际上我使用上面的代码来识别可以通过用户定义的装饰器装饰的方法。我想装饰所有的方法。但是我不能装饰
@classmethod
@staticmethod
。那么,有没有一种方法可以只提取一个类中的所有方法定义,这样只有那些类成员才能由我的用户定义的装饰器装饰
m3 *** <classmethod object at 0x1089afbb0>
m4 *** <staticmethod object at 0x1089afcd0>
<bound method C.m3 of <class '__main__.C'>>
<function C.m4 at 0x1050ab940>