Python物件導向靜態方法,類方法,屬性方法

來源:互聯網
上載者:User

標籤:icm   div   set   面向   none   注意   init   類的方法   屬性   

靜態方法(staticmethod名義上歸類管理,實際上在靜態方法裡訪問不到類或執行個體中的靜態屬性)
 1 class days(object): 2     def __init__(self, food): 3         self.food = food 4  5     @staticmethod  # 實際和類沒有關係 6     def tell(self): 7         print(‘這裡有%s,%s快來‘ % (self.food, ‘name‘)) 8  9 10 a = days(‘香蕉‘)11 a.tell(a)
類方法(classmethod只能訪問類變數,不能訪問執行個體變數)
 1 lass f2(object): 2     name = ‘大哥大大‘  # 類變數 3  4     def __init__(self, name): 5         self.name = name 6  7     @classmethod 8     def eat(self): 9         print(‘這裡有%s,【%s】‘ % (self.name, ‘類的方法‘))10 11 12 f2.eat()
屬性方法(把一個方法變成一個靜態屬性)
由屬性的定義和調用要注意一下幾點:1 定義時,在普通方法的基礎上添加 @property 裝飾器;2 定義時,屬性僅有一個self參數3 調用時,無需括弧屬性的定義有兩種方式:1 裝飾器 即:在方法上應用裝飾器2 靜態欄位 即:在類中定義值為property對象的靜態欄位
經典類,具有一種@property裝飾器:
 1 class f3(object): 2     def __init__(self, name): 3         self.name = name 4         self.__food = None 5  6     @property 7     def eat2(self): 8         print(‘這裡%s,【%s】‘ % (self.name, ‘在幹什麼‘)) 9 10 11 c = f3(‘阿豬‘)12 c.eat2
新式類,具有三種@property裝飾器,分別對應了三個被@property、@方法名.setter、@方法名.deleter修飾的方法。
 1 class f4(object): 2     def __init__(self, name): 3         self.name = name 4         self.__food = None 5  6     @property  # 把一個普通方法變為屬性方法,擷取 7     def eat(self): 8         print(‘這裡%s,【%s】‘ % (self.name, self.__food))  # 由於沒有參數self.__food在這沒有調用 9 10     @eat.setter  # 修改11     def eat(self, food):12         print(‘我要吃%s‘ % food)13         self.__food = food14 15     @eat.getter  # 刪除16     def eat(self):17         del self.__food18         print(‘刪除欄位self.__food‘)19 20 21 d = f4(‘阿豪‘)22 d.eat23 d.eat = ‘餃子‘24 del d.eat25 d.eat

 

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.