反射

1、反射

  • 手動輸入要運行的功能,反着去模塊裏找

2、相關函數

1. getattr(對象,屬性(字符串形式))

  • 從對象中獲取屬性
class Person:
    country = "China"

    def eat(self):
        print("-----eat-----")


obj = Person()
print(getattr(Person, "country"))  # China

# 類名.方法名(對象):方法調用的另外一種方式
getattr(Person, "eat")(obj)   # -----eat-----
getattr(obj, "eat")           # -----eat-----

2. hasattr(對象,屬性(字符串形式))

  • 判斷對象中是否有該屬性
class Person:
    country = "China"

    def eat(self):
        print("-----eat-----")


obj = Person()
print(hasattr(Person, "country"))  # True
print(hasattr(obj, "run"))         # False

 3. setattr(對象,屬性(字符串形式),值)

  • 若是屬性存在,則更改屬性的值
  • 若是屬性不存在,則新增屬性,並把值賦給屬性
class Person:
    country = "China"

    def eat(self):
        print("-----eat-----")

obj = Person() setattr(Person,
"eat", 3) # 此時內存中函數eat變爲eat = 3 obj.eat() # 報錯

 4. delattr(對象,屬性(字符串形式))

  • 刪除對象中的屬性
class Person:
    country = "China"

    def eat(self):
        print("-----eat-----")


obj = Person()
delattr(Person, "eat")
obj.eat()    # 'Person' object has no attribute 'eat'

 注:以上四個函數都是對加載到內存中的代碼進行操做的,並不會影響源代碼函數

5.總結:

1)對於屬性:測試

  • getattr(類名,屬性(字符串形式))               ----->類.屬性spa

  • getattr(對象,屬性(字符串形式))               ----->對象.屬性code

  • setattr(類名,屬性(字符串形式),值)       ----->修改類屬性的值對象

  • setattr(對象,屬性(字符串形式),值)       ----->給對象添加屬性
  • delattr(類名,屬性(字符串形式))              ----->刪除對象屬性
  • delattr(對象,屬性(字符串形式))              ----->報錯,對象沒有該屬性

2)對於實例方法:blog

  • getattr(類名,屬性(字符串形式))(對象)  ----->調用實例方法
  • getattr(對象,屬性(字符串形式))()    ----->調用實例方法
  • setattr(類名,屬性(字符串形式),值)      ----->若是屬性名存在,則修改方法,類型根據值的類型,若是不存在,則新增。給類新增函數時,須要考慮函數形參個數,若是無形參,則用對象.函數名調用報錯
  • setattr(對象,屬性(字符串形式),值)     ----->若是屬性名存在,則給對象添加屬性,類型根據值的類型,若是不存在,則新增
  • delattr(類名,屬性(字符串形式))            ----->刪除對象方法
  • delattr(對象,屬性(字符串形式))            ----->報錯,對象沒有該屬性

3、應用

場景:若是已知py文件有哪些方法,但想測試各方法做用,摘一摘本身想用的內容內存

# master.py文件裏內容:
def run():
    print("-----run-----")

def eat():
    print("-----eat-----")

def drink():
    print("-----drink-----")

 

代碼:字符串

import master
from types import FunctionType

while 1:
    gn = input("請輸入你要測試的功能:")
    
    if hasattr(master, gn):  # 若是master裏面有你要的功能
        # 獲取這個功能,並執行
        attr = getattr(master, gn)
        # 判斷是不是函數,只有函數才能夠被調用
        if isinstance(attr, FunctionType):
            attr()
        else:
            # 若是不是函數, 就打印
            print(attr)
相關文章
相關標籤/搜索