目录[-]
python获取当前类、函数、的名称,注释 # coding=utf-8 import sys class Test: def test1(self): """这是函数的注释""" pass def test2(self): print('当前方法的名称为:', sys._getframe().f_code.co_name) def test3(self): print('获取类下方法的注释信息:', self.test1.__doc__) def get_name(self): class_name = self.__class__.__name__ print('当前类名为:%s' % class_name) method_name = self.__dir__() print('当前类下所有方法的名称:', method_name) # 过滤获取的所有方法中的不需要的 filter_name = [] for i in method_name: if not i.startswith('__') and not i.startswith('_'): filter_name.append(i) print('过滤后的类方法:', filter_name) test = Test() test.test2() test.test3() test.get_name()
运行结果:
当前方法的名称为: test2
获取类下方法的注释信息: 这是函数的注释
当前类名为:Test
当前类下所有方法的名称: ['__module__', 'test1', 'test2', 'test3', 'get_name', '__dict__', '__weakref__', '__doc__', '__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__init__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
过滤后的类方法: ['test1', 'test2', 'test3', 'get_name']