043魔法方法:算术运算2

反运算:
  当左操作数不支持响应的操作时被调用
  如:对象(a+b),如果a对象有__add__方法,b对象的__radd__不会被调用
      只有当a对象的__add__方法没有实现或者不支持相应的操作才会调用b的__radd__方法

  如:>>> class Nint(int):
      ...     def __radd__(self,other):
      ...         return int.__sub__(self,other)
      ...
      >>> a = Nint(5)
      >>> b = Nint(3)
      >>> a + b
      2
      >>> 1 + b        当1没有找到响应的操作就按b的来,所以就执行了b的
      2
   如:>>> class Nint(int):
      ...     def __rsub__(self,other)
      ...         return int.__sub__(self,other)
      ...
      >>> a = Nint(5)
      >>> 3 - a          不应该是-2吗?为什么呢?
      2
   如:>>> class Nint(int):
      ...     def __rsub__(self,other):
      ...         return int.__sub__(other,self)   只要换一下这里的参数位置,结果就不同
      ...                                          
      >>> a = Nint(5)
      >>> 3 - a
      -2

一元操作符:
_neg_(self)     定义正号的行为:+x
_pos_(self)     定义负号的行为:-x
_abs_(self)     定义当被abs()调用时的行为
_invert_(self)  定义按位求反的行为:~x


练习:
1. 定义一个类,当实例化该类的时候,自动判断传入了多少个参数,并显示
 如:>>> class C:
   ...     def __init__(self,*args):
   ...         if not args:
   ...             print("wu")
   ...         else:
   ...             print("%d,:" % len(args)),
   ...             for each in args:
   ...                 print (each),
   ...

posted @ 2015-10-21 07:05  淡蓝色的天空很美  阅读(339)  评论(0编辑  收藏  举报