Python全栈之路-Day32
1 类的__slots__
#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/4/25
# 只能定义__slots__中规定的属性
#__slots__ 用于统一管理所有属性的定义
# 类变量,变量值可以是列表,元祖,或者可迭代对象,也可以是一个字符串(意味着所有实例只有一个数据属性)
class People:
__slots__ = ['x','y','z']
p = People()
p.x = 1
p.y = 2
p.z = 3
print(p.x,p.y,p.z)
p.v = 4 # 会抛出AttributeError异常
2 迭代器协议
#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/4/25
# __next__ __iter__
from collections import Iterable,Iterator
class Foo:
def __init__(self,start):
self.start = start
def __iter__(self):
return self
def __next__(self):
if self.start > 10:
raise StopIteration
num = self.start
self.start += 1
return num
f = Foo(0)
print(isinstance(f,Iterable))
print(isinstance(f,Iterator))
print(next(f))
print(next(f))
for item in f:
print(item)
# 利用迭代特性实现简单的range函数功能
class Range:
def __init__(self,start,end):
self.start = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.start > self.end:
raise StopIteration
num = self.start
self.start += 1
return num
for item in Range(0,2):
print(item)
3 类的__del__
#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/4/25
import time
class Open:
def __init__(self,filepath,mode='r',encode='utf-8'):
self.f = open(filepath,mode,encoding=encode)
def write(self):
pass
def __getattr__(self, item):
return getattr(self.f,item)
def __del__(self): # 当执行del f(并且引用计数为0时)时会触发这里的函数运行(程序结束时也会运行),一般执行一些清理操作
print('del func')
self.f.close()
f = Open('a.txt','w')
del f
time.sleep(5)
4 上下文管理协议
#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/4/25
with open('a.txt','r') as f:
print('--------->')
print('--------->')
print(f.read())
class Foo:
def __enter__(self):
print('enter...')
return self
def __exit__(self, exc_type, exc_val, exc_tb): # with代码块结束或者出现异常时执行
print('exit...')
print('exc_type',exc_type)
print('exc_val',exc_val)
print('exc_tb',exc_tb)
return True # 处理异常后返回True
with Foo() as f: # f = Foo().__enter__()
print('with Foo code area')
raise TypeError('Error value') # 会调用__exit__
5 元类
#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/4/26
# 元类 type
# 元类(type) --> 类(class) --> 对象(object)
# 1.通常的创建类的方式
class Foo: #
x = 1
def run(self):
pass
class test:
pass
print(Foo.__dict__)
print(Foo.__bases__)
print(type(Foo))
# 2.通过元类(type)创建类的方式
def run():
pass
class_name = 'Foo'
class_bases = (object,)
class_dict = {'x':1,'run':run}
Foo = type(class_name,class_bases,class_dict)
print(Foo.__dict__)
print(Foo.__bases__)
print(type(Foo))
# 元类应用
# 类的函数必须要写注释(__doc__)
class Mymeta(type):
def __init__(self,class_name,class_bases,class_dict):
for key in class_dict:
if callable(class_dict[key]):
if not class_dict[key].__doc__:
raise TypeError('小子,你没写注释,赶紧去写')
class Foo(metaclass=Mymeta): # Foo = Mymeta('Foo',(object,),{'x':1,'run':run}) 定义时会执行metaclass的__init__
x = 1
def __init__(self,name):
self.name = name
def run(self):
'run func'
print('running')
print(Foo.__dict__)
# 元类实例化过程
class Mymeta(type):
def __init__(self,class_name,class_bases,class_dict):
for key in class_dict:
pass
def __call__(self, *args, **kwargs):
print(self)
obj = self.__new__(self)
self.__init__(obj,*args,**kwargs)
return obj
class Foo(metaclass=Mymeta): # Foo = Mymeta('Foo',(object,),{'x':1,'__init__':__init__,'run':run}) 调用Mymeta的__init__
x = 1
def __init__(self,name):
self.name = name
def run(self):
'run func'
print('running')
f = Foo('egon') # 调用Mymeta的__call__
Python全栈之路-Day32的更多相关文章
- Python全栈之路目录结构
基础 1.Python全栈之路-----基础篇 2.Python全栈之路---运算符与基本的数据结构 3.Python全栈之路3--set集合--三元运算--深浅拷贝--初识函数 4.Python全栈 ...
- Python全栈之路----目录
Module1 Python基本语法 Python全栈之路----编程基本情况介绍 Python全栈之路----常用数据类型--集合 Module2 数据类型.字符编码.文件操作 Python全栈之路 ...
- Python全栈之路----常用模块----hashlib加密模块
加密算法介绍 HASH Python全栈之路----hash函数 Hash,一般翻译做“散列”,也有直接音译为”哈希”的,就是把任意长度的输入(又叫做预映射,pre-image),通过散列 ...
- python 全栈之路
目录 Python 全栈之路 一. Python 1. Python基础知识部分 2. Python -函数 3. Python - 模块 4. Python - 面对对象 5. Python - 文 ...
- Python全栈之路----函数----返回值
函数外部的代码想要获取函数的执行结果,就可以在函数里用return语句,把结果返回. def stu_register(name,age,course='PY',country='CN'): prin ...
- Python全栈之路----常用模块----软件开发目录规范
目录基本内容 log #日志目录 conf #配置目录 core/luffycity #程序核心代码目录 #luffycity 是项目名,建议用小写 libs/modules #内置模块 d ...
- Python全栈之路----常用模块----shutil模块
高级的 文件.文件包.压缩包 处理模块 参考Python之路[第四篇]:模块 #src是原文件名,fdst是新文件名 shutil.copyfileobj(fsrc, fdst[, len ...
- Python全栈之路----Python2与Python3
金角大王Alex python 之路,致那些年,我们依然没搞明白的编码 python2与python3的区别 py2 str = bytes 为什么有bytes? 是因为要表示图片.视频等二进制格式 ...
- Python全栈之路----函数进阶----装饰器
Python之路,Day4 - Python基础4 (new版) 装饰器 user_status = False #用户登录后改为True def login(func): #传入想调用的函数名 de ...
随机推荐
- swift -- 代理delegate
1.声明协议 protocol SecondDelagate { func sendValue(text : String!) -> Void } 2.声明代理属性 var delegate : ...
- Spring注解问题,[action中注入service失败
pring-mvc.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=" ...
- [Spark] - SparkCore程序优化总结
http://spark.apache.org/docs/1.6.1/tuning.html1) 代码优化 a. 对于多次使用的RDD,进行数据持久化操作(eg: cache.persist) b. ...
- Python--定时给Ta讲笑话
受到这篇文章的启发http://python.jobbole.com/84796/,我也动手写了个程序玩一玩. 接口请求说明: 接口请求地址http://api.1-blog.com/biz/bizs ...
- 关于EasyUI 1.5版Datagrid组件在空数据时无法显示"空记录"提示的BUG解决方法
问题:jQuery easyUI中Datagrid,在表格数据加载无数据的时候,如何显示"无记录"的提示语? 解决jQuery EasyUI 1.5.1版本的Datagrid,在处 ...
- 浅谈EL
一.了解EL 1.EL是从 JavaScript 脚本语言得到启发的一种表达式语言,它借鉴了 JavaScript 多类型转换无关性的特点.在使用 EL 从 scope 中得到参数时可以自动转换类型, ...
- mybatis基础学习4---懒加载和缓存
1:懒加载 1)在主配置文件设置(要放在配置文件最前面) <!-- 延迟加载配置,两个都必须同时有 --> <settings> <!-- lazyLoadingEnab ...
- mac下常用软件整理
1.非常好用的压缩管理软件(免费版):RAR Extrator Free 解压的中文不会产生乱码: 2.记笔记用的:有道笔记.Evernote 3.SVN管理软件:ConerStone 4.非常给力 ...
- Webstorm less watcher 配置
file > sttings > File watchers > 添加LESS watcher 配置如图:
- malloc函数及用法
动态存储分配在数组一章中,曾介绍过数组的长度是预先定义好的,在整个程序中固定不变.C语言中不允许动态数组类型.例如:int n;scanf("%d",&n);int a[n ...