python 常見內建函數setattr、getattr、delattr、setitem、getitem、delitem

來源:互聯網
上載者:User

標籤:通過   item   getattr   log   hello   根據   nbsp   成員   索引值   

常見內建函數
  • 內建函數:在類的內部,特定時機自動觸發的函數

  • 樣本1:setattr、getattr、delattr

  • class Person:    # def __init__(self, name):    #     self.name = name?    def __setattr__(self, key, value):        # 當設定對象成員屬性的時,系統會自動調用        print(key, value)        self.__dict__[key] = value?    def __getattr__(self, item):        # 當訪問不存在的對象屬性時,系統會自動調用        if item == ‘age‘:            return 123        else:            return ‘default‘?    def __delattr__(self, item):        # 當銷毀對象的成員屬性時,系統會自動調用        print(‘del‘, item)xiaoming = Person()
    每個對象都有一個成員屬性:dict     用於存放對象的屬性,包括動態添加的
print(xiaoming.dict)xiaoming.name = ‘小明‘print(xiaoming.name)print(xiaoming.dict)xiaoming.age = 18print(xiaoming.age) print(xiaoming.hello)del xiaoming.age

樣本2:setitem、getitem、delitem

  • 當對對象按照字典方式操作時,會自動觸發相關方法

  • 樣本:

    class Person:    # 當對對象按照字典設定索引值對時,會自動觸發該方法    def __setitem__(self, key, value):        # print(key, value)        self.__dict__[key] = value?    # 當對對象按照字典操作根據鍵擷取值時,會自動觸發該方法    def __getitem__(self, item):        # print(item)        return self.__dict__[item]?    # 當做字典操作,刪除索引值對時,自動觸發該方法    def __delitem__(self, key):        # print(key)        del self.__dict__[key]        p = Person()p[‘name‘] = ‘xiaoming‘print(p[‘name‘])?# 通過字典方式添加的索引值對,可以通過屬性的方式擷取print(p.name)print(p.dict)del p[‘name‘]

python 常見內建函數setattr、getattr、delattr、setitem、getitem、delitem

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.