运算符
正向运算符
正向运算符,这里指的是自身为左操作数的运算符
1,加法运算符(+)
__add__(self, other)
: 定义两个对象相加2,减法运算符(-)
__sub__(self, other)
: 定义两个对象相减3,乘法运算符(*)
__mul__(self, other)
: 定义两个对象相乘4,除法运算符(/)
__truediv__(self, other)
: 定义两个对象相除5,取整除法运算符(//)
__floordiv__(self, other)
: 定义两个对象整除6,取模运算符(%)
__mod__(self, other)
: 定义两个对象取模7,幂运算符(**)
__pow__(self, other)
: 定义两个对象求幂8,小于运算符(<)
__lt__(self, other)
: 定义对象小于9,大于运算符(>)
__gt__(self, other)
: 定义对象大于10,等于运算符(==)
__eq__(self, other)
: 定义对象相等
反向运算符
反向运算符,这里指的是自身为右操作数的运算符
1,
__radd__(self, other)
:对应于加法运算符的右侧操作数2,
__rsub__(self, other)
: 对应于减法运算符的右侧操作数3,
__rmul__(self, other)
: 对应于乘法运算符的右侧操作数4,
__rtruediv__(self, other)
: 对应于除法运算符的右侧操作数5,
__rfloordiv__(self, other)
: 对应于取整除法运算符的右侧操作数6,
__rmod__(self, other)
: 对应于取模运算符的右侧操作数7,
__rpow__(self, other)
: 对应于幂运算符的右侧操作数
使用自定义运算符的例子
以星期为例
class Week:
def __init__(self, today):
self.__week = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
if isinstance(today, str) and today in self.__week:
self.__today = self.__week.index(today)
elif isinstance(today, int) and 1 <= today <= 7:
self.__today = today - 1
elif isinstance(today, int):
raise ValueError("按照我们这里的规矩,1-7分别代表星期一到星期七,不可以使用其他数字")
else:
raise ValueError("非法的输入格式,请输入1-7代表星期一到星期日")
@property
def today(self):
return self.__week[self.__today]
def __add__(self, other):
if not isinstance(other, int):
raise ValueError("你是故意的吧?我们需要一个整数!")
return Week(self.__week[(self.__today + other) % 7])
def __sub__(self, other):
if not isinstance(other, int):
raise ValueError("你是故意的吧?我们需要一个整数!")
return Week(self.__week[(self.__today - other) % 7])
if __name__ == "__main__":
w1 = Week(1)
print(w1.today)
w2 = w1 + 3
print(w2.today)
为星期添加上反向的运算符
class Week:
def __init__(self, today):
self.__week = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
if isinstance(today, str) and today in self.__week:
self.__today = self.__week.index(today)
elif isinstance(today, int) and 1 <= today <= 7:
self.__today = today - 1
elif isinstance(today, int):
raise ValueError("按照我们这里的规矩,1-7分别代表星期一到星期七,不可以使用其他数字")
else:
raise ValueError("非法的输入格式,请输入1-7代表星期一到星期日")
@property
def today(self):
return self.__week[self.__today]
def __add__(self, other):
if not isinstance(other, int):
raise ValueError("你是故意的吧?我们需要一个整数!")
return Week(self.__week[(self.__today + other) % 7])
def __sub__(self, other):
if not isinstance(other, int):
raise ValueError("你是故意的吧?我们需要一个整数!")
return Week(self.__week[(self.__today - other) % 7])
def __radd__(self, other):
return self.__add__(other)
if __name__ == "__main__":
w1 = Week(1)
print(w1.today)
w2 = 3 + w1
print(w2.today)
需要额外注意的是,如果添加这样的代码,这样的做法是不对的
def __rsub__(self, other):
return self.__sub__(other)
因为很显然,week - 3和3 - week不是一回事,并且,在这个例子中,3 - week
可能没有明确的实际意义,因此不应当添加__rsub__