您的位置:首页 > 编程语言 > Python开发

Python学习笔记(二)——特殊方法(续)

2017-05-15 10:55 671 查看
代码及内容源自《Fluent Python》——Luciano Ramalho 著

实现中缀运算符的基本思路:创建新的对象,且不改变运算数(原运算对象)。

from math import hypot

class Vector:

def __init__(self, x=0,y=0):
self.x=x
self.y=y

def __repr__(self):
return 'Vector(%r,%r)' % (self.x, self.y)

def __abs__(self):
return hypot(self.x, self.y)

def __bool__(self):
return bool(abs(self))

def __add__(self, other):
x=self.x+other.x
y=self.y+other.y
return Vector(x,y)

def __mul__(self, scalar):
return Vector(self.x*scalar, self.y*scalar)


>>> v1=Vector(3,4)
>>> v2=Vector(2,1)
>>> v1+v2


Vector(5,5)


>>> abs(v1)


5.0


>>> v2*3


Vector(6,3)


>>> abs(v1*3)


15.0


默认情况下,用户定义类的实例被认为是TRUE,除非另外定义了__bool__或者__len__方法。 bool(x)会首先调用x.__bool__()并取得返回值。如果__bool__方法不存在,Python则会尝试调用x.__len__(),如果返回值是0,则bool为FALSE;否则,为TRUE。

class Tector:

def __init__(self, x=0,y=0):
self.x=x
self.y=y

def __repr__(self):
return 'Tector(%r,%r)' % (self.x, self.y)


>>> t0=Tector(0,0)
>>> bool(t0)


True


>>> v0=Vector(0,0)
>>> bool(v0)


False


在Vector的例子中,利用了向量的模是否为0来判断TRUE/FALSE。也可以采用另外一种更为高效的方法,来避免幂运算:

def __bool__(self):
return bool(self.x or self.y)


>>> t0=Tector(0,0)
>>> bool(t0)


False
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 对象 math