python操作符重寫,實現+操作符

cgdf 10年前發布 | 705 次閱讀 Python

import string
class spam:
    def init(self):
        self.eggs = 1
    def del(self):
        pass
    def add(self,other):
         rt = spam()
         rt.eggs = self.eggs + other.eggs
         return rt
    def coerce(self,other):
         rt = spam()
         if type(other) == type(rt):
             return (self,other)
         elif type(other) == type(''):
             e = string.atoi(other)
             rt.eggs = e
             return(self,rt)
         else:
             return None
    def radd(self,other):
         return self + other

if name == 'main': a = spam() b = spam() a = a + b print 'a now has', a.eggs, 'eggs' a = a + '24' print 'a now has', a.eggs, 'eggs' a = '24' + a print 'a now has', a.eggs, 'eggs' </pre>

 本文由用戶 cgdf 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!