Python getattr() 函数详解:动态获取属性与方法实例
本文详细介绍 Python 中 getattr() 函数的使用方法。通过字符串动态获取类或模块中的属性及方法实例,实现反射机制。内容涵盖从类中直接获取属性和函数,以及从模块中获取类对象的完整代码示例,帮助开发者理解动态加载与调用的实际应用。
getattr() 函数概述与反射机制
getattr() 函数允许通过方法名的字符串来调用相应的方法。其核心作用在于实现反射机制,即可以通过字符串形式的名称获取方法实例。这种机制使得开发者能够将类可能调用的方法配置在文件中,并在运行时根据配置动态加载和调用,从而提升代码的灵活性和可扩展性。
从类中获取属性和函数
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__]) # <module '__main__' from 'D:/脚本项目/lianxi/clazz/test.py'>
print(GetText) # <class '__main__.GetText'>
# 获取函数
print(getattr(GetText, "A")) # <function GetText.A at 0x00000283C2B75798>
# 获取函数返回值
getattr(GetText, "A")() # this is a staticmethod function
getattr(GetText(), "A")() # this is a staticmethod function
print(getattr(GetText, "B")) # <function GetText.B at 0x000001371BF55798>
# 非静态方法不可用
# getattr(GetText, "B")()
getattr(GetText(), "B")() # this is a func
print(getattr(GetText, "c")) # cc desc
print(getattr(GetText(), "c")) # cc desc
从模块中获取类对象
2. 从模块中获取类(通过类名字符串得到类对象)
新建 test1.py,具体代码如下:
#encoding:utf-8
import sys
import test
print(sys.modules[__name__])
# 从模块中获取类对象
class_name = getattr(test, "GetText")
print(class_name) # <class 'test.GetText'>
# 调用类的属性和函数
print(getattr(class_name, "A")) # <function GetText.A at 0x000001D637365678>
# 获取函数返回值
getattr(class_name, "A")() # this is a staticmethod function
getattr(class_name(), "A")() # this is a staticmethod function
print(getattr(class_name(), "B")) # <bound method GetText.B of <test.GetText object at 0x0000022D3B9EE348>>
# getattr(class_name, "B")() 非静态方法不可用
getattr(class_name(), "B")() # this is a func
# 获取属性值
print(getattr(class_name, "c")) # cc desc
print(getattr(class_name(), "c")) # cc desc
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









