python物件導向(二) 內建類方法__python

來源:互聯網
上載者:User
 內建方法  說明
 __init__(self,...)  初始化對象,在建立新對象時調用
 __del__(self)  釋放對象,在對象被刪除之前調用
 __new__(cls,*args,**kwd)  執行個體的產生操作
 __str__(self)  在使用print語句時被調用
 __getitem__(self,key)  擷取序列的索引key對應的值,等價於seq[key]
 __len__(self)  在調用內嵌函式len()時被調用
 __cmp__(stc,dst)  比較兩個對象src和dst
 __getattr__(s,name)  擷取屬性的值
 __setattr__(s,name,value)  設定屬性的值
 __delattr__(s,name)  刪除name屬性
 __getattribute__()  __getattribute__()功能與__getattr__()類似
 __gt__(self,other)  判斷self對象是否大於other對象
 __lt__(slef,other)  判斷self對象是否小於other對象
 __ge__(slef,other)  判斷self對象是否大於或者等於other對象
 __le__(slef,other)  判斷self對象是否小於或者等於other對象
 __eq__(slef,other)  判斷self對象是否等於other對象
 __call__(self,*args)  把執行個體對象作為函數調用

__init__():
__init__方法在類的一個對象被建立時,馬上運行。這個方法可以用來對你的對象做一些你希望的初始化。注意,這個名稱的開始和結尾都是雙底線。
代碼例子:

#!/usr/bin/python
# Filename: class_init.py
class Person:
    def __init__(self, name):
        self.name = name
    def sayHi(self):
        print 'Hello, my name is', self.name

p = Person('Swaroop')
p.sayHi()

輸出:
Hello, my name is Swaroop

   說明:__init__方法定義為取一個參數name(以及普通的參數self)。在這個__init__裡,我們只是建立一個新的域,也稱為name。注意它們是兩個不同的變數,儘管它們有相同的名字。點號使我們能夠區分它們。最重要的是,我們沒有專門調用__init__方法,只是在建立一個類的新執行個體的時候,把參數包括在圓括弧內跟在類名後面,從而傳遞給__init__方法。這是這種方法的重要之處。現在,我們能夠在我們的方法中使用self.name域。這在sayHi方法中得到了驗證。

__new__():
__new__()在__init__()之前被調用,用於產生執行個體對象.利用這個方法和類屬性的特性可以實現設計模式中的單例模式.單例模式是指建立唯一對象嗎,單例模式設計的類只能執行個體化一個對象.

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Singleton(object):
    __instance = None                       # 定義執行個體

    def __init__(self):
        pass

    def __new__(cls, *args, **kwd):         # 在__init__之前調用
        if Singleton.__instance is None:    # 產生唯一執行個體
            Singleton.__instance = object.__new__(cls, *args, **kwd)
        return Singleton.__instance

   

__getattr__()、__setattr__()和__getattribute__():
當讀取對象的某個屬性時,python會自動調用__getattr__()方法.例如,fruit.color將轉換為fruit.__getattr__(color).當使用指派陳述式對屬性進行設定時,python會自動調用__setattr__()方法.__getattribute__()的功能與__getattr__()類似,用於擷取屬性的值.但是__getattribute__()能提供更好的控制,代碼更健壯.注意,python中並不存在__setattribute__()方法.
代碼例子:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Fruit(object):
    def __init__(self, color = "red", price = 0):
        self.__color = color
        self.__price = price
       
    def __getattribute__(self, name):               # 擷取屬性的方法
        return object.__getattribute__(self, name)

    def __setattr__(self, name, value):
        self.__dict__[name] = value

if __name__ == "__main__":
    fruit = Fruit("blue", 10)
    print fruit.__dict__.get("_Fruit__color")       # 擷取color屬性
    fruit.__dict__["_Fruit__price"] = 5
    print fruit.__dict__.get("_Fruit__price")       # 擷取price屬性

   

__getitem__():
如果類把某個屬性定義為序列,可以使用__getitem__()輸出序列屬性中的某個元素.假設水果店中銷售多鐘水果,可以通過__getitem__()方法擷取水果店中的沒種水果
代碼例子:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class FruitShop:
     def __getitem__(self, i):      # 擷取水果店的水果
         return self.fruits[i]      

if __name__ == "__main__":
    shop = FruitShop()
    shop.fruits = ["apple", "banana"]
    print shop[1]
    for item in shop:               # 輸出水果店的水果
        print item,

輸出為:
banana
apple banana

   

__str__():
__str__()用於表示對象代表的含義,返回一個字串.實現了__str__()方法後,可以直接使用print語句輸出對象,也可以通過函數str()觸發__str__()的執行.這樣就把對象和字串關聯起來,便於某些程式的實現,可以用這個字串來表示某個類
代碼例子:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Fruit:     
    '''Fruit類'''               #為Fruit類定義了文檔字串
    def __str__(self):          # 定義對象的字串表示
        return self.__doc__

if __name__ == "__main__":
    fruit = Fruit()
    print str(fruit)            # 調用內建函數str()出發__str__()方法,輸出結果為:Fruit類
    print fruit                 #直接輸出對象fruit,返回__str__()方法的值,輸出結果為:Fruit類

   

__call__():
在類中實現__call__()方法,可以在對象建立時直接返回__call__()的內容.使用該方法可以類比靜態方法
代碼例子:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Fruit:
    class Growth:        # 內部類
        def __call__(self):
            print "grow ..."

    grow = Growth()      # 調用Growth(),此時將類Growth作為函數返回,即為外部類Fruit定義方法grow(),grow()將執行__call__()內的代碼
if __name__ == '__main__':
    fruit = Fruit()
    fruit.grow()         # 輸出結果:grow ...
    Fruit.grow()         # 輸出結果:grow ...

   

聯繫我們

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