赞
踩
一元运算符有+,-,~等,要想使这些一元运算符对对象起作用,需要在定义类的时候实现对应的魔术方法。
定义一个坐标类
class Coordinate(object): def __init__(self, x, y): self.x = x self.y = y def __pos__(self): return self def __neg__(self): return Coordinate(-self.x, -self.y) def __abs__(self): new_coordinate = Coordinate(abs(self.x), abs(self.y)) return new_coordinate def __invert__(self): new_coordinate = Coordinate(360 - self.x, 360 - self.y) return new_coordinate def __str__(self): return "(%s, %s)" % (self.x, self.y)
pos, neg, abs, __invert__都是魔术方法,他们的作用分别如下。
在对象前面使用+的时候会被调用,类中定义的是直接返回对象本身。
c1 = Coordinate(-100, -200)
print(c1)
print(+c1)
输出:
(-100, -200)
(-100, -200)
__neg__函数
在对象前面使用-的时候会后会被调用,这里返回坐标都是相反数的新对象。
c1 = Coordinate(-100, -200)
print(c1)
c2 = -c1
print(c2)
输出:
(-100, -200)
(100, 200)
在给对象执行abs的时候会被调用,这里返回坐标绝对值的新对象
c1 = Coordinate(-100, -200)
print(abs(c1))
输出:
(100, 200)
在对象前面使用~的时候会被调用,这里返回通过360减掉之后的新坐标对象。
c1 = Coordinate(-100, -200)
print(~c1)
输出:
(460, 560)
注意:这些魔术方法并不需要有返回值,比如上面的__neg__也可以修改对象本身,像下面这样。
def __neg__(self):
self.x = -self.x
self.y = -self.y
c1 = Coordinate(-100, -200)
print(c1)
-c1
print(c1)
输出:
(-100, -200)
(100, 200)
二元运算符是作用在两个元素上的,比如+,-,*,\都是二元运算符。
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : MagicBinaryOperator.py # @Author: RicLee # @Date : 2020/8/10 # @Desc : class Coordinate(object): def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): x = self.x + other.x y = self.y + other.y return Coordinate(x, y) def __sub__(self, other): x = self.x - other.x y = self.y - other.y return Coordinate(x, y) def __mul__(self, other): x = self.x * other.x y = self.y * other.y return Coordinate(x, y) def __truediv__(self, other): x = self.x / other.x y = self.y / other.y return Coordinate(x, y) def __floordiv__(self, other): x = self.x // other.x y = self.y // other.y return Coordinate(x, y) def __mod__(self, other): x = self.x % other.x y = self.y % other.y return Coordinate(x, y) def __str__(self): return "(%s, %s)" % (self.x, self.y) c1 = Coordinate(-100, -200) c2 = Coordinate(200, 300) c3 = c1 + c2 print(c3) c4 = c1 - c2 print(c4) c5 = c1 * c2 print(c5) c6 = c1 / c2 print(c6) c7 = c1 // c2 print(c7) c8 = c1 % c2 print(c8) 输出: (100, 100) (-300, -500) (-20000, -60000) (-0.5, -0.6666666666666666) (-1, -1) (100, 100)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。