码迷,mamicode.com
首页 > 其他好文 > 详细

上下文管理器的重写以计算术运算对应的魔术方法

时间:2019-05-23 00:26:43      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:odi   运行   add   encoding   ini   open   type   test   乘法   

一、上下文管理器

概念:上下文管理器是一个Python对象,为操作提供了额外的上下文信息,这种额外的信息,在
使用with语句初始化上下文,以及完成with 块中的所有代码是,采用可调用的形式。

实现一个上下文管理器需要实现两个方法:
1. object._enter_(self)

输入与此对象相关的运行时上下文。如果存在的话,with语句将绑定该方法的返回值到该语句的as字句中指
定的目标。

2. object._exit_(self,exc_type,exc_val,exc_tb)

exc_type:异常类型

exc_val :异常值

exc_tb :异常回溯追踪

退出于此对象相关的运行时上下文。

例子:
class MyOpen:

  def __init__(self, name, method, encoding = "utf8"):
    self.name = name
    self.method = method
    self.encoding = encoding

  def __enter__(self,):
     self.f = open(self.name, self.method, encoding= self.encoding)
    return self.f

  def __exit__(self, exc_type, exc_val, exc_tb):
    return self.f.close()

  with MyOpen("222.txt","w") as f:
    f.write("你好")

二 、算术运算符对应的魔术方法


__add__(self, other) 加法

__sub__(self, other) 减法

__add__(self, other) 乘法


__truediv__(self, other) 真除法
__floordiv__(self, other) 整数除法
__mod__(self, other) 取余运算

例子:
class Test:

  def __init__(self,data):
    self.data = data

  def __add__(self, other):
    return self.data + other.data

  def __mul__(self, other):
    return self.data * other.data


a = Test(10)
b = Test(20)
print(a*b)

上下文管理器的重写以计算术运算对应的魔术方法

标签:odi   运行   add   encoding   ini   open   type   test   乘法   

原文地址:https://www.cnblogs.com/666666pingzi/p/10909163.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!