1 类的__slots__

  1. #!/usr/bin/env python
  2. # __Author__: "wanyongzhen"
  3. # Date: 2017/4/25
  4. # 只能定义__slots__中规定的属性
  5. #__slots__ 用于统一管理所有属性的定义
  6. # 类变量,变量值可以是列表,元祖,或者可迭代对象,也可以是一个字符串(意味着所有实例只有一个数据属性)
  7. class People:
  8. __slots__ = ['x','y','z']
  9. p = People()
  10. p.x = 1
  11. p.y = 2
  12. p.z = 3
  13. print(p.x,p.y,p.z)
  14. p.v = 4 # 会抛出AttributeError异常

2 迭代器协议

  1. #!/usr/bin/env python
  2. # __Author__: "wanyongzhen"
  3. # Date: 2017/4/25
  4. # __next__ __iter__
  5. from collections import Iterable,Iterator
  6. class Foo:
  7. def __init__(self,start):
  8. self.start = start
  9. def __iter__(self):
  10. return self
  11. def __next__(self):
  12. if self.start > 10:
  13. raise StopIteration
  14. num = self.start
  15. self.start += 1
  16. return num
  17. f = Foo(0)
  18. print(isinstance(f,Iterable))
  19. print(isinstance(f,Iterator))
  20. print(next(f))
  21. print(next(f))
  22. for item in f:
  23. print(item)
  24. # 利用迭代特性实现简单的range函数功能
  25. class Range:
  26. def __init__(self,start,end):
  27. self.start = start
  28. self.end = end
  29. def __iter__(self):
  30. return self
  31. def __next__(self):
  32. if self.start > self.end:
  33. raise StopIteration
  34. num = self.start
  35. self.start += 1
  36. return num
  37. for item in Range(0,2):
  38. print(item)

3 类的__del__

  1. #!/usr/bin/env python
  2. # __Author__: "wanyongzhen"
  3. # Date: 2017/4/25
  4. import time
  5. class Open:
  6. def __init__(self,filepath,mode='r',encode='utf-8'):
  7. self.f = open(filepath,mode,encoding=encode)
  8. def write(self):
  9. pass
  10. def __getattr__(self, item):
  11. return getattr(self.f,item)
  12. def __del__(self): # 当执行del f(并且引用计数为0时)时会触发这里的函数运行(程序结束时也会运行),一般执行一些清理操作
  13. print('del func')
  14. self.f.close()
  15. f = Open('a.txt','w')
  16. del f
  17. time.sleep(5)

4 上下文管理协议

  1. #!/usr/bin/env python
  2. # __Author__: "wanyongzhen"
  3. # Date: 2017/4/25
  4. with open('a.txt','r') as f:
  5. print('--------->')
  6. print('--------->')
  7. print(f.read())
  8. class Foo:
  9. def __enter__(self):
  10. print('enter...')
  11. return self
  12. def __exit__(self, exc_type, exc_val, exc_tb): # with代码块结束或者出现异常时执行
  13. print('exit...')
  14. print('exc_type',exc_type)
  15. print('exc_val',exc_val)
  16. print('exc_tb',exc_tb)
  17. return True # 处理异常后返回True
  18. with Foo() as f: # f = Foo().__enter__()
  19. print('with Foo code area')
  20. raise TypeError('Error value') # 会调用__exit__

5 元类

  1. #!/usr/bin/env python
  2. # __Author__: "wanyongzhen"
  3. # Date: 2017/4/26
  4. # 元类 type
  5. # 元类(type) --> 类(class) --> 对象(object)
  6. # 1.通常的创建类的方式
  7. class Foo: #
  8. x = 1
  9. def run(self):
  10. pass
  11. class test:
  12. pass
  13. print(Foo.__dict__)
  14. print(Foo.__bases__)
  15. print(type(Foo))
  16. # 2.通过元类(type)创建类的方式
  17. def run():
  18. pass
  19. class_name = 'Foo'
  20. class_bases = (object,)
  21. class_dict = {'x':1,'run':run}
  22. Foo = type(class_name,class_bases,class_dict)
  23. print(Foo.__dict__)
  24. print(Foo.__bases__)
  25. print(type(Foo))
  26. # 元类应用
  27. # 类的函数必须要写注释(__doc__)
  28. class Mymeta(type):
  29. def __init__(self,class_name,class_bases,class_dict):
  30. for key in class_dict:
  31. if callable(class_dict[key]):
  32. if not class_dict[key].__doc__:
  33. raise TypeError('小子,你没写注释,赶紧去写')
  34. class Foo(metaclass=Mymeta): # Foo = Mymeta('Foo',(object,),{'x':1,'run':run}) 定义时会执行metaclass的__init__
  35. x = 1
  36. def __init__(self,name):
  37. self.name = name
  38. def run(self):
  39. 'run func'
  40. print('running')
  41. print(Foo.__dict__)
  42. # 元类实例化过程
  43. class Mymeta(type):
  44. def __init__(self,class_name,class_bases,class_dict):
  45. for key in class_dict:
  46. pass
  47. def __call__(self, *args, **kwargs):
  48. print(self)
  49. obj = self.__new__(self)
  50. self.__init__(obj,*args,**kwargs)
  51. return obj
  52. class Foo(metaclass=Mymeta): # Foo = Mymeta('Foo',(object,),{'x':1,'__init__':__init__,'run':run}) 调用Mymeta的__init__
  53. x = 1
  54. def __init__(self,name):
  55. self.name = name
  56. def run(self):
  57. 'run func'
  58. print('running')
  59. f = Foo('egon') # 调用Mymeta的__call__

Python全栈之路-Day32的更多相关文章

  1. Python全栈之路目录结构

    基础 1.Python全栈之路-----基础篇 2.Python全栈之路---运算符与基本的数据结构 3.Python全栈之路3--set集合--三元运算--深浅拷贝--初识函数 4.Python全栈 ...

  2. Python全栈之路----目录

    Module1 Python基本语法 Python全栈之路----编程基本情况介绍 Python全栈之路----常用数据类型--集合 Module2 数据类型.字符编码.文件操作 Python全栈之路 ...

  3. Python全栈之路----常用模块----hashlib加密模块

    加密算法介绍 HASH       Python全栈之路----hash函数 Hash,一般翻译做“散列”,也有直接音译为”哈希”的,就是把任意长度的输入(又叫做预映射,pre-image),通过散列 ...

  4. python 全栈之路

    目录 Python 全栈之路 一. Python 1. Python基础知识部分 2. Python -函数 3. Python - 模块 4. Python - 面对对象 5. Python - 文 ...

  5. Python全栈之路----函数----返回值

    函数外部的代码想要获取函数的执行结果,就可以在函数里用return语句,把结果返回. def stu_register(name,age,course='PY',country='CN'): prin ...

  6. Python全栈之路----常用模块----软件开发目录规范

    目录基本内容 log  #日志目录 conf  #配置目录 core/luffycity  #程序核心代码目录  #luffycity 是项目名,建议用小写 libs/modules  #内置模块 d ...

  7. Python全栈之路----常用模块----shutil模块

    高级的 文件.文件包.压缩包 处理模块   参考Python之路[第四篇]:模块     #src是原文件名,fdst是新文件名 shutil.copyfileobj(fsrc, fdst[, len ...

  8. Python全栈之路----Python2与Python3

    金角大王Alex  python 之路,致那些年,我们依然没搞明白的编码 python2与python3的区别 py2 str = bytes 为什么有bytes? 是因为要表示图片.视频等二进制格式 ...

  9. Python全栈之路----函数进阶----装饰器

    Python之路,Day4 - Python基础4 (new版) 装饰器 user_status = False #用户登录后改为True def login(func): #传入想调用的函数名 de ...

随机推荐

  1. spring知识点全部复习

    一. 专业术语 侵入式设计 引入框架,对现有的类的结构有影响,即需要实现或继承某些特定类.如:Struts框架 非侵入式设计 引入框架,对现有的类结构没有影响.如:Hibernate.Spring 控 ...

  2. 复杂SQL代码实例

    DECLARE @begin DATETIME,@end DATETIME,@shanghutype INT, @beginshanghuarea BIGINT ,@endshanghuarea bi ...

  3. 10分钟精通SharePoint - SharePoint拓扑结构

    SharePoint服务器角色:前端,应用程序和数据库服务器 应用程序服务:搜索.Office文档.User Profile和App等应用服务器 数据库类型:内容数据库.应用程序数据库和配置数据库 规 ...

  4. pom.xml配置文件配置jar(不用记,快速配置)

    1:网址:http://mvnrepository.com/ 2:在搜索栏搜索要用的框架;例如spring *以下为示例

  5. 《Machine Learning》系列学习笔记之第二周

    第二周 第一部分 Multivariate Linear Regression Multiple Features Note: [7:25 - θT is a 1 by (n+1) matrix an ...

  6. 基于EM的多直线拟合

    作者:桂. 时间:2017-03-22  06:13:50 链接:http://www.cnblogs.com/xingshansi/p/6597796.html 声明:欢迎被转载,不过记得注明出处哦 ...

  7. Spring-java代理技术总结

    Spring 中采用JDk的动态代理和CGLib代理技术在运行期间织入增强,所以用户不需要装备特殊的编译器或者类装载器就可以使用AOP功能. 要使用jdk的动态代理,目标类必须实现接口,而CGLib代 ...

  8. vue渐变淡入淡出轮播图

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  9. 初步认识Thymeleaf:简单表达式和标签。(二)

    本篇文章是对上篇文章中Thymeleaf标签的补充. 1.th:each:循环,<tr th:each="user,userStat:${users}">,userSt ...

  10. Android编码规范

    Android-Code-Style 1.约定 Activity.onCreate(),Fragment.onActivityCreated(),紧跟成员变量后,方法内部保持简单,尽量只调用initX ...