Python運算子多載用法執行個體分析

來源:互聯網
上載者:User
本文執行個體講述了Python運算子多載用法。分享給大家供大家參考。具體如下:

在Python語言中提供了類似於C++的運算子重在功能:

一下為Python運算子重在調用的方法如下:

Method Overloads Call for
__init__ 建構函式 X=Class()
__del__ 解構函式 對象銷毀
__add__ + X+Y,X+=Y
__or__ | X|Y,X|=Y
__repr__ 列印轉換 print X,repr(X)
__str__ 列印轉換 print X,str(X)
__call__ 調用函數 X()
__getattr_ 限制 X.undefine
__setattr__ 取值 X.any=value
__getitem__ 索引 X[key],
__len__ 長度 len(X)
__cmp__ 比較 X==Y,X__lt__ 小於 X__eq__ 等於 X=Y
__radd__ Right-Side + +X
__iadd__ += X+=Y
__iter__ 迭代 For In

1. 減法重載

class Number:    def __init__(self, start):      self.data = start    def __sub__(self, other): #minus method      return Number(self.data - other)  number = Number(20)  y = number – 10 # invoke __sub__ method class Number:   def __init__(self, start):     self.data = start   def __sub__(self, other): #minus method     return Number(self.data - other) number = Number(20) y = number – 10 # invoke __sub__ method

2. 迭代重載

class indexer:    def __getitem__(self, index): #iter override      return index ** 2 X = indexer()  X[2]  for i in range(5):    print X[i] class indexer:   def __getitem__(self, index): #iter override     return index ** 2 X = indexer() X[2] for i in range(5):   print X[i]

3. 索引重載

class stepper:    def __getitem__(self, i):      return self.data[i]  X = stepper()  X.data = 'Spam' X[1] #call __getitem__  for item in X: #call __getitem__    print item class stepper:   def __getitem__(self, i):     return self.data[i] X = stepper() X.data = 'Spam' X[1] #call __getitem__ for item in X: #call __getitem__    print item

4. getAttr/setAttr重載

class empty:    def __getattr__(self,attrname):      if attrname == 'age':        return 40     else:        raise AttributeError,attrname  X = empty()  print X.age #call__getattr__  class accesscontrol:    def __setattr__(self, attr, value):      if attr == 'age':        # Self.attrname = value loops!        self.__dict__[attr] = value      else:        print attr        raise AttributeError, attr + 'not allowed' X = accesscontrol()  X.age = 40   #call __setattr__  X.name = 'wang' #raise exception class empty:   def __getattr__(self,attrname):     if attrname == 'age':       return 40     else:       raise AttributeError,attrname X = empty() print X.age #call__getattr__ class accesscontrol:   def __setattr__(self, attr, value):     if attr == 'age':       # Self.attrname = value loops!       self.__dict__[attr] = value     else:       print attr       raise AttributeError, attr + 'not allowed' X = accesscontrol() X.age = 40   #call __setattr__ X.name = 'wang' #raise exception

5. 列印重載

class adder:    def __init__(self, value=0):      self.data = value    def __add__(self, other):      self.data += other  class addrepr(adder):    def __repr__(self):      return 'addrepr(%s)' % self.data  x = addrepr(2) #run __init__  x + 1    #run __add__  print x   #run __repr__ class adder:   def __init__(self, value=0):     self.data = value   def __add__(self, other):     self.data += other class addrepr(adder):   def __repr__(self):     return 'addrepr(%s)' % self.data x = addrepr(2) #run __init__ x + 1    #run __add__ print x   #run __repr__

6. Call調用函數重載

class Prod:    def __init__(self, value):      self.value = value    def __call__(self, other):      return self.value * other  p = Prod(2) #call __init__  print p(1) #call __call__  print p(2) class Prod:   def __init__(self, value):     self.value = value   def __call__(self, other):     return self.value * other p = Prod(2) #call __init__ print p(1) #call __call__ print p(2)

7. 解構函式重載

class Life:    def __init__(self, name='name'):      print 'Hello', name      self.name = name    def __del__(self):      print 'Goodby', self.name  brain = Life('Brain') #call __init__  brain = 'loretta'  # call __del__

希望本文所述對大家的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.