python-物件導向(三)——類的特殊成員

來源:互聯網
上載者:User

標籤:

類的特殊成員

 

1. __doc__     表示類的描述資訊
class Foo:    """ 描述類資訊,這是用於看片的神奇 """    def func(self):        passprint Foo.__doc__==============描述類資訊,這是用於看片的神奇

 

2. __module__ 和  __class__   __module__ 表示當前操作的對象在哪個模組    __class__     表示當前操作的對象的類是什麼

 

3. __init__
構造方法,通過類建立對象時,自動觸發執行。
class Foo:    def__init__(self, name):        self.name = name        self.age = 18obj = Foo(‘wupeiqi‘)# 自動執行類中的 __init__ 方法

  

  4. __del__

析構方法,當對象在記憶體中被釋放時,自動觸發執行。

註:此方法一般無須定義,因為Python是一門進階語言,程式員在使用時無需關心記憶體的分配和釋放,因為此工作都是交給Python解譯器來執行,所以,解構函式的調用是由解譯器在進行記憶體回收時自動觸發執行的。

class Foo:    def__del__(self):        pass

 

5. __call__   對象後面加括弧,觸發執行。   註:構造方法的執行是由建立對象觸發的,即:對象 = 類名() ;而對於 __call__ 方法的執行是由對象後加括弧觸發的,即:對象() 或者 類()()
class Foo:    def__init__(self):        passdef__call__(self, *args, **kwargs):        print‘__call__‘obj = Foo() # 執行 __init__obj()       # 執行 __call__

 

6. __dict__    類或對象中的所有成員

  上文中我們知道:類的普通欄位屬於對象;類中的靜態欄位和方法等屬於類,即:

 

 

class Province:    country = ‘China‘    def__init__(self, name, count):        self.name = name        self.count = count    def func(self, *args, **kwargs):        print‘func‘# 擷取類的成員,即:靜態欄位、方法...
print Province.__dict__# 輸出:{‘country‘: ‘China‘, ‘__module__‘: ‘__main__‘, ‘func‘: <function func at 0x10be30f50>, ‘__init__‘: <function __init__ at 0x10be30ed8>, ‘__doc__‘: None}# 擷取 對象obj1 的成員
obj1 = Province(‘HeBei‘,10000)print obj1.__dict__# 輸出:{‘count‘: 10000, ‘name‘: ‘HeBei‘}

 

7. __str__ 如果一個類中定義了__str__方法,那麼在列印 對象 時,預設輸出該方法的傳回值。
class Foo:    def__str__(self):        return‘wupeiqi‘obj = Foo()print obj# 輸出:wupeiqi

 

8、 __getitem__ __setitem__ __delitem__  用於索引操作,如字典。以上分別表示擷取、設定、刪除資料

 

#!/usr/bin/env python# -*- coding:utf-8 -*- class Foo(object):     def __getitem__(self, key):        print ‘__getitem__‘,key     def __setitem__(self, key, value):        print ‘__setitem__‘,key,value     def __delitem__(self, key):        print ‘__delitem__‘,key obj = Foo() result = obj[‘k1‘]      # 自動觸發執行 __getitem__obj[‘k2‘] = ‘wupeiqi‘   # 自動觸發執行 __setitem__del obj[‘k1‘]           # 自動觸發執行 __delitem__

 

9、__getslice__、__setslice__、__delslice__ 該三個方法用於分區操作,如:列表       slice  :  切片 切割
#!/usr/bin/env python# -*- coding:utf-8 -*- class Foo(object):     def __getslice__(self, i, j):        print ‘__getslice__‘,i,j     def __setslice__(self, i, j, sequence):        print ‘__setslice__‘,i,j     def __delslice__(self, i, j):        print ‘__delslice__‘,i,jobj = Foo() obj[-1:1]                   # 自動觸發執行 __getslice__obj[0:1] = [11,22,33,44]    # 自動觸發執行 __setslice__del obj[0:2]                # 自動觸發執行 __delslice__

 

10. __iter__  用於迭代器,之所以列表、字典、元組可以進行for迴圈,是因為類型內部定義了 __iter__
  第一步:
class Foo(object):    passobj = Foo()for i in obj:    print i    # 報錯:TypeError: ‘Foo‘ object is not iterable  可迭代的

第二步:

#!/usr/bin/env python# -*- coding:utf-8 -*-class Foo(object):        def__iter__(self):        passobj = Foo()for i in obj:    print i# 報錯:TypeError: iter() returned non-iterator of type ‘NoneType‘

第三步:

#!/usr/bin/env python# -*- coding:utf-8 -*-class Foo(object):    def__init__(self, sq):        self.sq = sq    def__iter__(self):        return iter(self.sq)obj = Foo([11,22,33,44])for i in obj:    print i

以上步驟可以看出,for迴圈迭代的其實是  iter([11,22,33,44]) ,所以執行流程可以變更為:

 

#!/usr/bin/env python# -*- coding:utf-8 -*- obj = iter([11,22,33,44]) for i in obj:    print iFor迴圈文法內部#!/usr/bin/env python# -*- coding:utf-8 -*-obj = iter([11,22,33,44])while True:    val = obj.next()    print val

  

  11. __new__ 和 __metaclass__
閱讀以下代碼:
class Foo(object):     def __init__(self):        pass obj = Foo()   # obj是通過Foo類執行個體化的對象
  上述代碼中,obj 是通過 Foo 類執行個體化的對象,其實,不僅 obj 是一個對象,Foo類本身也是一個對象,因為在Python中一切事物都是對象。   如果按照一切事物都是對象的理論:obj對象是通過執行Foo類的構造方法建立,那麼Foo類對象應該也是通過執行某個類的 構造方法 建立。 
print type(obj) # 輸出:<class ‘__main__.Foo‘>     表示,obj 對象由Foo類建立print type(Foo) # 輸出:<type ‘type‘>              表示,Foo類對象由 type 類建立

所以,obj對象是Foo類的一個執行個體Foo類對象是 type 類的一個執行個體,即:Foo類對象 是通過type類的構造方法建立。

那麼,建立類就可以有兩種方式:  a). 普通方式  
class Foo(object):     def func(self):        print ‘hello wupeiqi‘
  b).特殊方式(type類的建構函式)
 
def func(self):    print ‘hello wupeiqi‘ Foo = type(‘Foo‘,(object,), {‘func‘: func})#type第一個參數:類名#type第二個參數:當前類的基類#type第三個參數:類的成員
    ==》 類 是由 type 類執行個體化產生

 

 

 

 

 

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.