Python学习笔记2

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 再创建的列表使用的是默认函数。重写后就得到如下结果:
在这里插入图片描述
然后对列表排序:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值