Python:类的附加内容

with语句

	语法:
    	with 表达式1[as 变量1],
        	表达式[as 变量2],....
        	语句块
	作用:
    	使用于对资源进行访问的场合,确保使用过程中不管是否
    		发生异常,都会执行必须的‘清理’操作,并释放资源。
    如:
        文件使用后自动关闭,线程中锁的自动获取和释放等
    说明:
    	执行表达式,用as 子句中的变量绑定生成的对象
    	with语句并不改变异常的状态 

环境管理器

	类内有__enter__和__exit__实例方法的类被称为环境管理器
	__enter__将在进入with语句时被调用,并返回由as变量管理的对象
	__exit__将在离开with语句时被调用,且可以用参数来判断在离开with
		语句时是否发生异常,并作出相应的处理
示例:
class a:
    def __enter__(self):
        '''此方法必须返回由as 绑定的对象'''
        print("a类已进入with语句")
    def __exit__(self,e_type,e_value,e_tb):
        '''e_type绑定异常类型,没有异常时绑定none
        e_value绑定错误对象,没有异常时绑定none
        e_tb绑定追踪对象,没有异常时绑定none'''
        print("a类已离开with语句")
        if e_type is None:
            print('我是没有异常时退出with语句')
        else:
            print('有离开with语句时有异常发生')
            print(e_type)
            print(e_tb)
            print(e_value)
with a() as A:
    print('这是with语句内部的一条语句')
    int(input('输入整数'))
print('程序正常退出')


运算符重载

什么是运算符重载
    让自定义的类生成的对象(实例)能够使用运算符进行操作
作用:
    让自定义的类的实例像内建对象一样使用运算符
    让程序简洁易读
    对自定义的对象将运算符赋值新的运算规则
算数运算符重载
方法名                运算符和表达式   说明
__add__(self, rhs)      self +  rhs  加法
__sub__(self, rhs)      self -  rhs  减法
__mul__(self, rhs)      self *  rhs  乘法
__truediv__(self, rhs)  self /  rhs  除法
__floordiv__(self, rhs) self // rhs  地板除
__mod__(self, rhs)      self %  rhs  求余
__pow__(self, rhs)      self ** rhs  幂运算

 **rhs (right hands side)  右手边**
	示例:
	class MyNumber:
    	def __init__(self,v):
        	self.v=v
    	def __repr__(self):
        	return 'MyNumber(%d)'%self.v
    	def __sub__(self,other):
        	v=self.v-other.v
        	return MyNumber(v)#创建一个对象并返回


	n1=MyNumber(100)
	n2=MyNumber(200)
	n3=n1.__sub__(n2)
	# n3=n1+n2   等同于n3=n1.__add__(n2)
	print(n1,'-',n2,'=',n3)
说明:
	运算符重载的方法和参数已经有固定的含义,不建议改变原来的意义
反向算数运算符的重载
	当运算符左侧为内建类型,右侧为自定义类型进行算数运算时,会出
	现typeerror错误
	因无法修改内建类型的代码来实现运算符重载,此时需要使用反向
	算数运算符重载来完成重载
 方法名                运算符和表达式   说明
__radd__(self, lhs)      lhs +  self  加法
__rsub__(self, lhs)      lhs -  self  减法
__rmul__(self, lhs)      lhs *  self  乘法
__rtruediv__(self, lhs)  lhs /  self  除法
__rfloordiv__(self, lhs) lhs // self  地板除
__rmod__(self, lhs)      lhs %  self  求余
__rpow__(self, lhs)      lhs ** self  幂运算

复合赋值运算符重载

	以复合赋值算数运算符 x+=y为例,此运算符会优先调用 x.__ia
	dd__(y)方法		时会将复合赋值运算符拆解为x=x+y然后再调用
	x=x.add(y)方法,如果再不存在__add__方法则会触发typeerror 异常
		其他复合赋值运算符也具有相同的规则
方法名                  运算符和表达式               说明
__iadd__(self,rhs)          self+=rhs                
__isub__(self,rhs)          self-=rhs
__imul__(self,rhs)          self*=rhs
__itruediv__(self,rhs)      self/=rhs
__ifloordiv__(self,rhs)     self//=rhs
__imod__(self,rhs)          self%=rhs
__ipow__(self,rhs)          self**=rhs

比较运算符的重载:

 方法名              运算符和表达式   说明
__lt__(self, rhs)    self <  rhs    小于
__le__(self, rhs)    self <= rhs    小于等于
__gt__(self, rhs)    self >  rhs    大于
__ge__(self, rhs)    self >= rhs    大于等于
__eq__(self, rhs)    self == rhs    等于
__ne__(self, rhs)    self != rhs    不等于
l. little
e. equal
g. greater
t. than

位运算符重载:

方法名              运算符和表达式   说明
__and__(self, rhs)    self &  rhs    位与
__or__(self, rhs)     self |  rhs    位或
__xor__(self, rhs)    self ^  rhs    位异或
__lshift(self, rhs)   self << rhs    左移
__rshift(self, rhs)   self >> rhs    右移

反向位运算符重载:

方法名              运算符和表达式   说明
__rand__(self, lhs)   lhs &  self     位与
__ror__(self, lhs)    lhs |  self     位或
__rxor__(self, lhs)   lhs ^  self     位异或
__rlshift(self, lhs)  lhs << self     左移
__rrshift(self, lhs)  lhs >> self     右移

复合赋值位运算符重载:

方法名              运算符和表达式   说明
__iand__(self, rhs)    self &=  rhs    位与
__ior__(self, rhs)     self |=  rhs    位或
__ixor__(self, rhs)    self ^=  rhs    位异或
__ilshift(self, rhs)   self <<= rhs    左移
__irshift(self, rhs)   self >>= rhs    右移

一元运算符的重载

方法名          运算符和表达式  说明
__neg__(self)     - self      负号
__pos__(self)     + self      正号
__insert__(self)  ~ self      取反

语法:
class 类名:
   	def __xxx__(self):
      	 ....

in / not in 运算符重载

  	 方法名             运算符和表达式
__contains__(self, e)    e in self    

索引和切片运算符的重载

L[0]
L[::2]
方法名                  运算符和表达式  说明
__getitem__(self, i)    x = self[i]  取值
__setitem__(self, i, v) self[i] = v  赋值
__delitem__(self, i)    del self[i]  删除索引

slice 构造函数

作用:
	用于创建一个slice切片对象,此对象存储一个切片
	的起始值,终止值和步长信息,默认都为None
格式:
	slice(start=None, stop=None, step=None)
slice对象的属性
	s.start 切片的起始值 默认为None
	s.stop  切片的终止值,默认为None
	s.step  切片的步长,默认为None

特性属性 @property

实现其它语言所拥有的 getter 和 setter 功能

作用:
	用来模拟一个属性
	通过@property装饰器可以对模拟的属性赋值和取值
  		加以控制
	class Student:
    	def __init__(self, score=0):
        	self.__score = score

    	def set_score(self, v):
        	'''setter'''
        	assert 0 <= v <= 100, "成绩超出范围"
        	self.__score = v

    	def get_score(self):
        	'''getter'''
        	return self.__score

	s = Student()
	print(s.get_score())
	s.set_score(99)
	# s.set_score(1000)  # 报错
	print(s.get_score())

	# print(s.score)  # 取值
	# s.score = 99    # 正确赋值
	# s.score = 10000  # 赋值报错
	# print(s.score)

猜你喜欢

转载自blog.csdn.net/qq_43494793/article/details/83614956