当前位置: 移动技术网 > IT编程>脚本编程>Python > Python getattr()函数使用方法代码实例

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

2020年08月11日  | 移动技术网IT编程  | 我要评论
getatter()通过方法名字符串调用方法,这个方法最主要的作用就是实现反射机制,也就是说可以通过字符串获取方法实例,这样就可以把一个类可能要调用的方法放到配置文件里,需要的时候进行动态加载。1:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网