標籤:pos port 分享 屬性 學習 成員 col not strong
反射 # 通過字串的形式對對象中的成員進行操作(擷取/尋找/添加/刪除)。
操作的內建函數:
1.擷取 getattr(object, name)
# 去對象object中擷取name的內容
class Foo: def __init__(self, name, age): self.name = name self.age = ageobj = Foo(‘Lemon147‘, 18)v = getattr(obj, ‘name‘)print(v)>>> Lemon147add = getattr(obj, ‘add‘, ‘not find!‘) #如果對象obj中有屬性add則返回self.add的值,否則返回‘not find‘!print(add)>>> not find!
getattr
2.尋找 hasattr(object, name)
# 檢查對象object中是否有name
class Foo: def __init__(self, name, age): self.name = name self.age = ageobj = Foo(‘Lemon147‘, 18)setattr(obj, ‘add‘, ‘123‘)print(getattr(obj, ‘add‘))delattr(obj, ‘add‘)add = hasattr(obj, ‘add‘)print(add)>>>False
hasattr
3.添加 setattr(object, name,value)
# 在對象object中設定name的值為value
class Foo: def __init__(self, name, age): self.name = name self.age = ageobj = Foo(‘Lemon147‘, 18)setattr(obj, ‘add‘, ‘123‘)add = hasattr(obj, ‘add‘)print(add) >>> Trueprint(getattr(obj, ‘add‘)) >>>123
setattr
4.刪除 delattr(object, name)
# 刪除對象object中的成員name
class Foo: def __init__(self, name, age): self.name = name self.age = ageobj = Foo(‘Lemon147‘, 18)setattr(obj, ‘add‘, ‘123‘)print(getattr(obj, ‘add‘))delattr(obj, ‘add‘)add = hasattr(obj, ‘add‘)print(add)
deaattr
註:getattr,hasattr,setattr,delattr對模組的修改都在記憶體中進行,並不會影響檔案中真實內容。
應用情境
根據輸入或選擇,動態調用不同的模組或功能。(同字典-dictionary 通過key,查詢對應的value類似。)
def s1(): return ‘首頁‘def s2(): return ‘新聞‘def s3(): return ‘精華‘
test002
import test002foo = Truewhile foo: inp = input(‘請輸入您要查詢的內容,輸入‘Q’退出:‘) #輸入‘s1’執行‘首頁’ if hasattr(test002, inp): v = getattr(test002, inp) print(v()) elif inp == ‘Q‘: break else: print(‘輸入有誤‘)
test001
python學習筆記__反射