反射
反射指的是通過 ”字串“ 對物件的屬性或方法進行操作,
反射的方法有:
hasattr:通過 ”字串“ 判斷物件的屬性或方法是否存在
getattr:通過 ”字串“ 獲取物件的屬性值或方法
setattr:通過 ”字串“ 設定物件的屬性值
delattr:通過 ”字串“ 洗掉物件的屬性或方法
注意:反射的四個方法都是python內置
1、hasattr
通過 ”字串“ 判斷物件的屬性或方法是否存在
class Foo: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def func(self): pass foo_obj = Foo(10, 20, 30)
# hasattr:通過字串 "x"、"y"、"z" 判斷物件中是否存在屬性 print(hasattr(foo_obj, "x")) print(hasattr(foo_obj, "y")) print(hasattr(foo_obj, "z")) # hasattr:通過字串 "func" 判斷物件中是否存在該方法 print(hasattr(foo_obj, "func"))
執行結果:
True
True
True
True
2、getattr
通過 ”字串“ 獲取物件的屬性值或方法
class Foo: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def func(self): pass foo_obj = Foo(10, 20, 30)
# getattr:通過字串 "x"、"y"、"z" 來獲取物件屬性 print(getattr(foo_obj, "x")) print(getattr(foo_obj, "y")) print(getattr(foo_obj, "z")) # getattr:通過字串 "func" 來獲取物件的系結方法 print(getattr(foo_obj, "func")) # 若該屬性不存在,則回傳 "不存在,默認值" print(getattr(foo_obj, "a", "不存在,默認值"))
執行結果:
10 20 30 <bound method Foo.func of <__main__.Foo object at 0x00000000021B6508>> 不存在,默認值
3、setattr
通過 ”字串“ 設定物件的屬性值;若該屬性不存在,即添加 ,若存在,即修改
class Foo: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def func(self): pass foo_obj = Foo(10, 20, 30) # setattr:通過字串 "x" 設定(修改)物件的屬性值 print(getattr(foo_obj, "x")) setattr(foo_obj, "x", 100) print(getattr(foo_obj, "x")) # 若不存在該屬性,即添加該屬性 setattr(foo_obj, "a", 200) print(getattr(foo_obj, "a"))
執行結果:
10 100 200
4、delattr
通過 ”字串“ 洗掉物件的屬性或方法
class Foo: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def func(self): pass foo_obj = Foo(10, 20, 30) # delattr:通過字串 "x" 洗掉物件的屬性或方法 print(hasattr(foo_obj, "x")) delattr(foo_obj, "x") print(hasattr(foo_obj, "x"))
執行結果:
True
False
5、反射的應用場景
場景:用于校驗用戶輸入
class FileControl: def run(self): while True: # 讓用戶輸入上傳或下載功能的命令 user_input = input('請輸入上傳(upload)或下載(download)功能, 輸入"quit"退出>>> ').strip() # 通過用戶的字串,呼叫相應的方法 if hasattr(self, user_input): func = getattr(self, user_input) # func --> upload , func --> download func() elif user_input == "quit": break else: print("輸入有誤...") def upload(self): print("檔案正在上傳...") def download(self): print("檔案正在下載...") file_obj = FileControl() file_obj.run()
執行結果:
請輸入上傳(upload)或下載(download)功能, 輸入"quit"退出>>> upload 檔案正在上傳... 請輸入上傳(upload)或下載(download)功能, 輸入"quit"退出>>> download 檔案正在下載... 請輸入上傳(upload)或下載(download)功能, 輸入"quit"退出>>> quit
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/194407.html
標籤:Python
下一篇:蜘蛛爬行策略或網路抓取
