Python 类中的特殊方法(Magic Method)
https://docs.python.org/3/reference/datamodel.html#special-method-names
Python中拥有以双下划线开头并结尾的特殊方法,比如最常用的__init__()方法。
类中常见特殊方法
和比较相关的:
方法名 | 如何使用 |
---|---|
__ 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 |
lt() 是内建函数sort()用来比较的函数。所以通过重写(override) lt() 可以直接用sort()对自建类的对象进行排序
与数学相关的:
方法名 | 如何使用 |
---|---|
__ 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 |
与字符串相关的:
方法名 | 如何使用 |
---|---|
__ str__(self) | str(self) |
__ repr__(self) | repr(self) |
__ len__(self) | len(self) |
str(object)* 是内建函数format()和print()都会用的函数。它用于说明如何打印信息,它的返回值必须是字符串。
Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.*
repr() 是内建函数,通过正式的字符串表示对象,通过它可以重新创建拥有相同值的新对象
Called by the repr() built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <…some useful description…> should be returned. The return value must be a string object. If a class defines __ repr__() but not __ str__(), then __ repr__() is also used when an “informal” string representation of instances of that class is required.
实例
class Student:
#重写__init__()函数
def __init__(self,sname,mscore,cscore,escore):
self.sname = sname #姓名sname,
self.mscore = mscore #数学分数mscore,
self.cscore = cscore #语文分数cscore,
self.escore = escore #英语分数escore
self.total = mscore + cscore + escore #总分数total
#重写__lt__()函数,通过总分数进行排序
def __lt__(self, other):
return self.toal < other.total
#重写__str__()函数,用于打印信息
def __str__(self):
return '%s:语文 %d,数学 %d,英语 %d'%(self.name,self.cscore,self.mscore,self.escore)
#实例
student1 = Student('Tom',90,80,70)
student2 = Student('Jack',85,90,80)
print(student1)
print(sorted([student1,student2]))
运行结果:
因为没有重写__repr__(),所以根据student1,student2 再创建的列表使用的是默认函数。重写后就得到如下结果:
然后对列表排序: