运算符重载
在Python中,并没有像其他语言(如C++)中那样的内置机制来重载运算符。但是,你可以通过定义特定的方法来模拟运算符重载的行为。
以下是一些常见运算符以及它们对应的特殊方法:
加法:+ 对应 __add__
减法:- 对应 __sub__
乘法:* 对应 __mul__
除法:/ 对应 __truediv__
取模:% 对应 __mod__
幂运算:** 对应 __pow__
位运算:
位运算:>> 对应 __rshift__
位运算:& 对应 __and__
位运算:| 对应 __or__
位运算:^ 对应 __xor__
class Operator(object):
def __init__(self, x):
self.x = x
def __add__(self, other):
return self.x + other.x * 3
o1 = Operator(1)
o2 = Operator(3)
print(o1 + o2)
class Operator(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return self.x * other.x + self.y * other.y
o1 = Operator(1, 2)
o2 = Operator(3, 4)
print(o1 + o2)
类的多态
python中的多态也可以通过方法重写进行。
同一个方法,不同对象显式的结果不同。
class Animal(object):
name = '动物'
age = 0
def speak(self):
print("动物的声音")
class Dog(Animal):
def speak(self):
print("汪汪汪")
class Cat(Animal):
def speak(self):
print("喵喵喵")
a = Animal()
d = Dog()
c = Cat()
a.speak()
d.speak()
c.speak()