1. 程式人生 > 程式設計 >Python getattr()函式使用方法程式碼例項

Python getattr()函式使用方法程式碼例項

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。