Pyhton学习——Day28

2022-12-02,,

#上下文协议:文件操作时使用with执行
# with open('a.txt','w',encoding='utf-8') as f1:
# with语句,为了让一个对象兼容with语句,必须在这个对象的类中声明__enter__和__exit__方法
# class Open:
# def __init__(self,name):
# self.name = name
# def __enter__(self):
# print('如果出现with语句,__enter__就被触发')
# def __exit__(self, exc_type, exc_val, exc_tb):
# print('with语句一旦执行完毕,__exit__就会被触发')
# with Open('a.txt') as f1:
# print('各种执行代码块')
# 如果出现with语句,__enter__就被触发
# 各种执行代码块
# with语句一旦执行完毕,__exit__就会被触发
########################################################################################################
# __exit__()中的三个参数分别代表异常类型,异常值和追溯信息,with语句中代码块出现异常,则with后的代码都无法执行
# class Open:
# def __init__(self,name):
# self.name = name
# def __enter__(self):
# print('如果出现with语句,__enter__就被触发')
# def __exit__(self, exc_type, exc_val, exc_tb):
# print('with语句一旦执行完毕,__exit__就会被触发')
# with Open('a.txt') as f1:
# print('各种执行代码块')
# raise AttributeError ('抛出一个超级异常')
# print('我就不会被执行了')
# 如果出现with语句,__enter__就被触发
# 各种执行代码块
# with语句一旦执行完毕,__exit__就会被触发
# Traceback (most recent call last):
# File "F:/Python/PythonLeaning/每日学习打卡/Day28.py", line 27, in <module>
# raise AttributeError ('抛出一个超级异常')
# AttributeError: 抛出一个超级异常
########################################################################################################
# class Open:
# def __init__(self,name):
# self.name = name
# def __enter__(self):
# print('如果出现with语句,__enter__就被触发')
# def __exit__(self, exc_type, exc_val, exc_tb):
# print('with语句一旦执行完毕,__exit__就会被触发')
# return True #执行时即使报错也当错误不存在
# with Open('a.txt') as f1:
# print('各种执行代码块')
# raise AttributeError ('抛出一个超级异常')
# print('我就会继续被执行了,因为__exit__被加了return True')
########################################################################################################
# 用途或者说好处:
# 1.使用with语句的目的就是把代码块放入with中执行,with结束后,自动完成清理工作,无须手动干预
# 2.在需要管理一些资源比如文件,网络连接和锁的编程环境中,可以在__exit__中定制自动释放资源的机制,
# 你无须再去关系这个问题,这将大有用处
########################################################################################################
# NameError:异常类-->class
# name 'asda' is not defined-->异常值
# Traceback -->追溯信息
########################################################################################################
#描述符
# 一、描述符本身应该定义成新式类(继承了object类),被代理的类也应该是新式类
# 二、必须把描述符定义成这类的类属性,不能低昂一道构造函数中
# 三、要严格遵循优先级
# python是弱类型语言:不用定义变量的类型就可以使用
# def test(x):
# print('---->',x)
# test('a')
# test(1)
# 为python加上类型检测:
# class Typed:
# def __init__(self,key,excepted_type):
# self.key= key
# self.excepted = excepted_type
# def __get__(self, instance, owner):
# print('get方法')
# # print('instance 参数【%s】'%instance)
# # print('owner 参数【%s】'%owner)
# return instance.__dict__[self.key]
# def __set__(self, instance, value):
# print('set方法')
# # print('instance 参数【%s】'%instance)
# # print('value 参数【%s】'%value)
# # print('---->',instance)
# if not isinstance(value,self.excepted):
# print('你传入的类型不是字符串,错误')
# return
# else:
# instance.__dict__[self.key] = value
# class People:
# name = Typed('name',str)
# age = Typed('age',int)
# # age = Typed('age')
# def __init__(self,name,age,salary):
# self.name = name #触发的是被代理,而不是实例化
# self.age = age
# self.salary = salary
# # p1 = People('panda',18,2100.1245)
# p2 = People(9527,18,29213)
# # print(p1.name)
# # p2 = People(1,10,20)
# # print(p1.__dict__)
# # print(p1.name)
# print(p2.name)
########################################################################################################
# 类的装饰器原理
# def deco(obj):
# print('----------->>>>',obj)
# obj.x = 1
# obj.y = 2
# obj.x = 3
# return obj
# # @deco #dtest = deco(test)
# # def test():
# # print('test函数运行')
# # test()
# @deco #Foo = deco(Foo)
# class Foo:
# pass
# f1 = Foo()
# print(Foo.__dict__)
########################################################################################################
# def Typed(*args,**kwargs):
# def deco(obj):
# print('---->>',kwargs)
# print('---->>', obj)
# for key ,val in kwargs.items():
# setattr(obj,key,val)
# return obj
# print('==>',kwargs)
# return deco
# @Typed(x = 1,y = 2,z = 3)
# class Foo:
# pass
# print(Foo.__dict__)
# @Typed(name = 'egg')
# class Bar:
# pass
# 用装饰器为类增加一个数据属性
########################################################################################################
# 再看property
# 一个静态属性property本质就是实现了get,set,delete三种方法
# class Lazyproperty:
# def __init__(self,func):
# self.func = func
# def __get__(self, instance, owner):
# print('我是get方法')
# if instance is None:
# return self
# res = self.func(instance)
# setattr(instance,self.func.__name__,res)
# return res
# class Room:
# def __init__(self,name,width,length):
# self.name = name
# self.width = width
# self.length = length
# @ Lazyproperty #area = property(area) 给Room添加了一个类对象
# def area(self):
# return self.width * self.length
# @property #test = property(test)
# def area1(self):
# return self.width * self.length
# @property
# def test(self):
# return ('返回一个值')
# r1 = Room('toilet',1,2)
# #实例调用
# # print(r1.area)
# # print(Room.__dict__)
# # 类调用
# #print(Room.area)
# print(r1.area)
# print(r1.__dict__)
# print(r1.area)
# print(r1.area)
# print(r1.area)
# print(r1.test)
#函数运行时要把实例本身传入,而不是类
#描述符用来代理类的属性
# 类调用的instance传入的是None,实例调用的instance传入的是self
########################################################################################################
# 延迟计算的功能:对于已经运行的函数,将结果存储在内存中,下一次调用方法的时候就不再运行函数而是直接调用
# (本质就是把一个函数属性利用装饰器原理做成一个描述符:类的属性字典中函数名为key,value为描述符类产生的对象)
# 描述符是很多高级库和框架的重要工具之一,描述符是通常使用到装饰器或者元类的大型框架中的一个组件
# class Foo:
# @property
# def AAA(self):
# print('get的时候运行我')
# return self
# @AAA.setter
# def AAA(self,value):
# print('set的时候运行我',value)
# @AAA.deleter
# def AAA(self,value):
# print('delete的时候运行我')
# f1 = Foo()
# f1.AAA = 'aaa'
########################################################################################################
# class Foo:
# def get_AAA(self):
# print('get的时候运行我')
# return self
# def set_AAA(self,value):
# print('set的时候运行我')
# def del_AAA(self):
# print('delete的时候运行我')
# AAA = property(get_AAA,set_AAA,del_AAA)
# # 只有属性在AAA定义property后才能定义AAA,setter,AAA,delete
# f1 = Foo()
# f1.AAA = 'aaa'
########################################################################################################
# metaclass--->元类
# class Foo:
# pass
# f1 = Foo() #f1是通过Foo实例化对象
# python中一切皆是对象,类本身也是一个对象,当使用关键字class的时候,python解释器在加载class的时候就会创建一个对象
# (这里的对象指的是类而非类的实例)
# f1是Foo这个类产生的对象,而Foo本身也是对象
# print(type(f1))
# print(type(Foo))
#————————————————————————————————————————————————————#
# 什么是元类?
# 元类是类的类,是类的模板
# 元类是用来控制如何创建类的,正如类是创建对象的模板一样
# 元类的实例为类,正如类的实例对象(f1对象是Foo类的一个实例,Foo类是type类的一个实例)
# type是python的一个內建元类,用来控制生成类,python中任何class定义的类其实都是type实例化的对象
# type(类名,object,属性字典)
# class Foo:
# def __init__(self,name):
# self.name = name
# pass
# print(Foo)
# def __init__(self,name,age):
# self.name = name
# self.age = age
# FFo = type('FFo',(object,),{'x':1,'__init__':__init__})
# print(FFo)
# print(FFo.__dict__)
# f1 = FFo('alex',19)
# print(f1.name)
# class MyType(type):
# def __init__(self,a,b,c):
# print('元素的构造函数执行')
# # print(a)
# # print(b)
# # print(c)
# def __call__(self, *args, **kwargs):
# print('====>')
# print(self)
# print(*args,**kwargs)
# obj = object.__new__(self)
# self.__init__(obj,*args,**kwargs) #实际在执行Foo.__init__()
# class Foo(metaclass=MyType): #type('Foo',(object),{}) MyType传入了4个参数
# def __init__(self,name):
# self.name = name
# f1 = Foo('OneName')
# 练习一:在元类中控制把自定义类的数据属性都变成大写

Pyhton学习——Day28的相关教程结束。

《Pyhton学习——Day28.doc》

下载本文的Word格式文档,以方便收藏与打印。