这篇文章将为大家详细讲解有关Python中如何使用getattr()函数,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
getatter()通过方法名字符串调用方法,这个方法最主要的作用就是实现反射机制,也就是说可以通过字符串获取方法实例,这样就可以把一个类可能要调用的方法放到配置文件里,需要的时候进行动态加载。
1: 可以从类中获取属性和函数
新建test.py文件,代码如下:
# encoding:utf-8 import sys class GetText(): def __init__(self): pass @staticmethod def A(): print("this is a staticmethod function") def B(self): print("this is a func") c = "cc desc" if __name__ == '__main__': print(sys.modules[__name__]) #print(GetText) # # 获取函数 print(getattr(GetText, "A")) # # 获取函数返回值 getattr(GetText, "A")() # this is a staticmethod function getattr(GetText(), "A")() # this is a staticmethod function print(getattr(GetText, "B")) # # 非静态方法不可用 # getattr(GetText, "B")() getattr(GetText(), "B")() # this is a func print(getattr(GetText, "c")) # cc desc print(getattr(GetText(), "c")) # cc desc