Python getattr()函数使用方法代码实例

作者:yaominghui 时间:2022-03-04 03:30:51 

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
标签:Python,getattr,函数
0
投稿

猜你喜欢

  • 关于ASP循环表格的问题之解答[比较详细]

    2011-04-08 11:14:00
  • 对python中的logger模块全面讲解

    2021-01-17 00:49:17
  • asp长文章分页显示思路

    2007-08-23 13:54:00
  • SQL语句练习实例之一——找出最近的两次晋升日期与工资额

    2011-10-24 20:16:42
  • C#调用Python的URL接口的示例

    2022-08-22 21:49:27
  • SQL server不支持utf8 php却用utf8的矛盾问题解决方法

    2023-07-20 12:01:28
  • 使用css2.1实现多重背景、多重边框效果[译]

    2010-08-23 16:32:00
  • php基于curl主动推送最新内容给百度收录的方法

    2023-11-22 04:46:44
  • 用JS开发页面动画效果时的一个设计思路

    2008-02-03 15:12:00
  • wxpython自定义下拉列表框过程图解

    2023-11-14 04:01:18
  • 详解python函数传参是传值还是传引用

    2023-11-13 13:25:58
  • Python3内置模块之base64编解码方法详解

    2021-04-01 15:45:24
  • SQL Server创建索引教程

    2010-07-02 21:09:00
  • PHP For循环字母A-Z当超过26个字母时输出AA,AB,AC

    2023-10-07 08:09:10
  • Django 使用Ajax进行前后台交互的示例讲解

    2023-08-03 03:57:47
  • asp数据转换函数示例

    2008-04-13 06:52:00
  • php tpl模板引擎定义与使用示例

    2023-11-14 22:04:49
  • 关于Python中的main方法教程

    2021-12-30 08:31:37
  • python for循环赋值问题

    2023-01-26 05:56:32
  • 数字人整合动网论坛的方法

    2009-05-29 18:23:00
  • asp之家 网络编程 m.aspxhome.com