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__]) # <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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“Python getattr()函数使用方法代码实例”评论...
更新日志
2024年10月07日
2024年10月07日
- 群星《前途海量 电影原声专辑》[FLAC/分轨][227.78MB]
- 张信哲.1992-知道新曲与精丫巨石】【WAV+CUE】
- 王翠玲.1995-ANGEL【新艺宝】【WAV+CUE】
- 景冈山.1996-我的眼里只有你【大地唱片】【WAV+CUE】
- 群星《八戒 电影原声带》[320K/MP3][188.97MB]
- 群星《我的阿勒泰 影视原声带》[320K/MP3][139.47MB]
- 纪钧瀚《胎教古典音乐 钢琴与大提琴的沉浸时光》[320K/MP3][148.91MB]
- 刘雅丽.2001-丽花皇后·EMI精选王【EMI百代】【FLAC分轨】
- 齐秦.1994-黄金十年1981-1990CHINA.TOUR.LIVE精丫上华】【WAV+CUE】
- 群星.2008-本色·百代音乐人创作专辑【EMI百代】【WAV+CUE】
- 群星.2001-同步过冬AVCD【环球】【WAV+CUE】
- 群星.2020-同步过冬2020冀待晴空【环球】【WAV+CUE】
- 沈雁.1986-四季(2012梦田复刻版)【白云唱片】【WAV+CUE】
- 纪钧瀚《胎教古典音乐 钢琴与大提琴的沉浸时光》[FLAC/分轨][257.88MB]
- 《国语老歌 怀旧篇 3CD》[WAV/分轨][1.6GB]