python學習之路--屬性

來源:互聯網
上載者:User

標籤:字元   使用者   val   set   顯示   print   分享   setattr   調用順序   

本篇文章主要是分享pyton裡面的屬性的設定和擷取使用:Property屬性的內建函數:

1.__getattr__(self, name) 
  -定義當使用者試圖擷取一個不存在的屬性時的行為
2.__getattribute__(self, name)
  -定義當該類的屬性被訪問時的行為
3.__setattr__(self, name, value)
  -定義當一個屬性被設定時的行為
4.__delattr__(self, name)
  -定義當一個屬性被刪除時的行為
  一個對象的屬性在對象裡面其實是由一個字典表來管理的,通過object.__dict__可以查看,返回的是一個字典表,顯示的是每一個屬性名稱的字串和屬性相對應的值;

以上內建函數調用順序是:

1.設定當前的屬性,會調用__setattr__(self, name, value)方法來設定當前的屬性,如果屬性存在,直接設定屬性的值,如果屬性不存在,則會增加一個該屬性

2.擷取屬性的值,會調用__getattribute__(self, name)方法來擷取,調用後如果屬性存在,則直接擷取屬性的值,如果屬性不存在,則會調用__getattr__(self, name)方法來擷取

3.刪除屬性調用__delattr__(self, name)方法來刪除屬性

可以運行以下例子不難看出對象的屬性的設定和調用:

 

# -*- coding: utf-8 -*-
"""

@author: zzj

"""

class PropertyTest:
  def __init__(self, size = 10):
    self.size = size
  def __getattribute__(self, name):
    print("正在訪問該類的屬性")
    return super().__getattribute__(name)
  def __getattr__(self, name):
    print("該屬性不存在")
  def __setattr__(self, name, value):
    print("設定當前屬性")
    return super().__setattr__(name, value)
  def __delattr(self, name):
    print("刪除當前屬性")
    super().__delattr__(name)

  def GetSize(self):
    return self.size
  def SetSize(self, value):
    self.size = value
  def DelSize(self):
    del self.size
  x = property(GetSize, SetSize, DelSize)


C = PropertyTest()
print(C.size)

C.x = 1
print(C.size)
print(C.x)

del C.x
print(C.size)

 

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.