1、和比较相关的魔法方法
方法 | 用途 |
---|---|
__eq__(self, other) | self == other |
__ne__(self, other) | self != other |
__lt__(self, other) | self < other |
__gt__(self, other) | self > other |
__le__(self, other) | self <= other |
__ge__(self, other) | self >= other |
示例代码:
class Person(object):
def __init__(self, name, age):
self.__name = name
self.__age = age
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
self.__name = name
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
self.__age = age
def __eq__(self, other):
return self.__age == other.__age
def __ne__(self, other):
return self.__age != other.__age
def __lt__(self, other):
return self.__age < other.__age
def __gt__(self, other):
return self.__age > other.__age
def __le__(self, other):
return self.__age <= other.__age
def __ge__(self, other):
return self.__age >= other.__age
p1 = Person('zhangsan',20)
p2 = Person('lisi',20)
p3 = Person('wangwu',18)
p4 = Person('zhaoliu',25)
print(p1==p2)
print(p1==p3)
print(p1!=p2)
print(p1!=p4)
print(p1<p2)
print(p1<p4)
print(p1>p3)
print(p1>=p2)
print(p1<=p4)
2、和数学相关的魔法方法
方法 | 用途 |
---|---|
__add__(self, other) | self + other |
__sub__(self, other) | self - other |
__mul__(self, other) | self * other |
__floordiv__(self, other) | self // other |
__truediv__(self, other) | self / other |
__mod__(self, other) | self % other |
__pow__(self, other) | self ** other |
示例代码:
class Point(object):
def __init__(self, x, y):
self.__x = x
self.__y = y
@property
def x(self):
return self.__x
@x.setter
def x(self, x):
self.__x = x
@property
def y(self):
return self.__y
@y.setter
def y(self, y):
self.__y = y
def __add__(self, other):
return Point(self.__x + other.__x, self.__y + other.__y)
def __sub__(self, other):
return Point(self.__x - other.__x, self.__y - other.__y)
def __str__(self):
return '('+str(self.__x)+','+str(self.__y)+')'
p1 = Point(4,5)
p2 = Point(1,2)
p3 = p1+p2
p4 = p1-p2
print(p1)
print(p2)
print('p1+p2:',p3)
print('p1-p2:',p4)
3、其他种类的魔术方法
方法 | 用途 |
---|---|
__str__(self) | str(self) |
__repr__(self) | repr(self) |
__len__(self) | len(self) |
示例代码:
class Word(object):
def __init__(self, text):
self.text = text
def __len__(self):
return len(self.text)
def __str__(self):
return self.text
__repr__ = __str__
w = Word('hello world')
print(len(w))
print(w)