面向对象之魔术方法
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2020/5/19 22:00 # @Author : "小多肉" # @Email : 1021181701@qq.com # @File : 面向对象之魔术方法.py # @Software: PyCharm """TODO: 第一题:基于pymysql模块实现一个数据库操作的上下文管理器(目的:实现自动关闭连接对象和游标) 第二题:自定义一个列表类型,实现对象可以之间可以 使用 - 来进行操作 # 要求:如果一个对象减去另一个对象,则把和被减对象中一样的数据给删除掉 # 如下: li1 = MyList([11, 22, 33, 44]) li2 = MyList([1, 22, ]) res = li1 - li2 # res 打印的结果为[11,33,44] """ import pymysql class DBContext: def __init__(self, host=None, port=3306, user='root', password='', charset='utf8', database=None, **kwargs ): self.conn = pymysql.connect(host=host, port=port, user=user, password=password, charset=charset, database=database, **kwargs ) self.cursor = self.conn.cursor() def __enter__(self): return self.conn, self.cursor def __exit__(self, exc_type, exc_val, exc_tb): self.cursor.close() self.conn.close() class ListSub: def __init__(self,li:list): self.li = li def __sub__(self, other): for i in other.li: if i in self.li: self.li.remove(i) return self.li def __add__(self, other): return self.li + other.li if __name__ == '__main__': print("----------------------第一题------------------------") with DBContext(host="192.168.5.20",password="love520",database="love") as (my_conn,my_cursor): sql = "select to_date('2020-12-01' ,'YYYY-MM-DD') - to_date('2020-05-20','YYYY-MM-DD') from dual;" my_cursor.execute(sql) my_conn.commit() data = my_cursor.fetchone() print(data) print("----------------------第二题------------------------") li1 = ListSub([11, 22, 33, 44]) li2 = ListSub([1, 22, ]) res = li1 - li2 print(res) res2 = li1 + li2 print(res2)