python學習筆記__反射

來源:互聯網
上載者:User

標籤: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學習筆記__反射

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.