Python运算符重载

来源:互联网 发布:大同seo大牛 编辑:程序博客网 时间:2024/05/16 15:48

class Parent:    parentAttr = 100    def __init__(self):        print('调用父类构造函数')    def parentMethod(self):        print('调用父类方法')    def setAttr(self, attr):        self.parentAttr = attr    def getAttr(self):        print('父类属性:', self.parentAttr)    def __del__(self):        print('父类析构')        class Child(Parent):    def __init__(self):        print('调用子类构造函数')    def childMethod(self):        print('调用子类方法 child method')    def __del__(self):        print('子类析构')    def __str__(self):        return 'class name:Child'    def __repr__(self):        return 'ClassName:Child'            c = Child()c.childMethod()c.parentMethod()c.setAttr(200)c.getAttr()if isinstance( c, Parent ):    print('yes')if issubclass( Child, Parent ):    print('yes')#del cprint(repr(c)) #输出ClassName:Child,repr(c)会调用c.__repr__(self) print(str(c)) #输出class name:Child,str(c)会调用c.__str__(self)

参考:http://www.w3cschool.cc/python/python-object.html

7.1    减法重载class Number:       def __init__(self, start):           self.data = start            def __sub__(self, other): #minus method           return Number(self.data - other)        def show(self):        print(self.data)  number = Number(20)   y = number - 10 # invoke __sub__ method  y.show()  #输出107.2    迭代重载class indexer:       def __getitem__(self, index): #iter override           return index ** 2  X = indexer()   X[2]   for i in range(5):       print (X[i])  #X[i]调用X.__getitem__(i)7.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)  '''输出:Spam'''7.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__print(X.__dict__)X.name = 'wang' #raise exception  7.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__  输出addrepr(3)7.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__   输出2print (p(2))   #输出47.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__,输出Hello Brainbrain = 'loretta'    # call __del__ ,输出Goodby Brain,brain指向了别的对象,原来的类对象要释放,故调用析构函数7.8 加法函数重载class Test(object):            def __init__(self, value):          self.value = value                def __add__(self, x):          return self.value + x.value    a = Test(3)  b = Test(4)  print (a + b)

ref: http://blog.csdn.net/mafuli007/article/details/7754499


0 0
原创粉丝点击