python中類的魔術方法

來源:互聯網
上載者:User

標籤:python   class   methods   

目的:學習python中class的magic methods,提高編程效率。


環境:ubuntu 16.4   python 3.5.2


在學習class是一定會接觸到它的magic methods,比如常用__init__,形式都是前後有雙底線。除了這個必須的,還有其他有用的方法,下面大概的介紹一下。

運算魔法方法:

__add__ 用作 +

__sub__ 用作 -

__mul__ 用作 *

__truediv__用作/

__floordiv__用作//

__mod__用作%

__pow__用作**

__and__用作&

__xor__用作^

__or__用作|

舉例說明:

class SpecialString:    def __init__(self, cont):        self.cont = cont            def __truediv__(self, other):        line = ‘=‘ * len(other.cont)        return rn.join([self.cont, line, other.cont])     spam = SpecialString(‘spam‘)hello = SpecialString(‘Helo world!‘)print(spam/hello)# 結果>>>spam============Hello world!>>>

x + y 相當於 x.__add__(y), 但是如果x沒有__add__方法,且x和y是不同的類,那麼就會檢查y有沒有__radd__,有則表示為y.__radd__(x),沒有則出現TypeError,所有的megic methods都有r methods。


比較魔法方法:

__lt__  用作 <

__le__ 用作 <=

__eq__ 用作 ==

__ne__ 用作 !=

__gt__ 用作 >

__ge__ 用作 >=

 如果__ne__不存在,則返回__eq__的方向。

舉例說明:

class SpecialString:    def __init__(self, cont):        self.cont = cont            def __gt__(self, other):        for index in range(len(other.cont) + 1):            result = other.cont[:index] + ‘>‘ + self.cont            result += ‘>‘ + other.cont[index:]            print(result)        spam = SpecialString(‘spam‘)eggs = SpecialString(‘eggs‘)spam > eggs# result>>>>spam>eggse>spam>ggseg>spam>gsegg>spam>seggs>spam>>>類似容器的魔術方法:__len__用作 len()__getitem__ 用作進行索引__setitem__ 用作分配索引__delitem__ 用作刪除索引__iter__ 用作迭代對象__contains__用作in舉例說明:class VagueList:    def __init__(self, cont):        self.cont = cont            def __getitem__(self, index):        return self.cont[index + random.randint(-1, 1)]        def __len__(self):        return random.randint(0, len(self.cont) * 2)        vague_list = VagueList([‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘])print(len(vague_list))print(len(vague_list))print(vague_list[2])print(vague_list[2])#result>>>22CD>>>

  參考文檔來源:sololearn


本文出自 “RickyHuL” 部落格,請務必保留此出處http://rickyh.blog.51cto.com/10934856/1952167

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.