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

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

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com

稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!

昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。

这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。

而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?