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的更多相关文章

  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. KoaHub.JS基于Node.js开发的Koa 生成验证码插件代

    ccap node.js generate captcha using c++ library CImg without install any other lib or software node- ...

  2. 算法模板——AC自动机

    实现功能——输入N,M,提供一个共计N个单词的词典,然后在最后输入的M个字符串中进行多串匹配(关于AC自动机算法,此处不再赘述,详见:Aho-Corasick 多模式匹配算法.AC自动机详解.考虑到有 ...

  3. 3.java的hello word.继承.泛型.反射.配置项.数据库操作.lombok

    迷迷茫茫的开始了第一步.弄个hello word.结果这第一小步也不是那么的顺利. 明明照着图敲的.可就是没有运行选项. 为此还百度了一下.也没有什么答案.最后只能老老实实的看了.结果还是粗心的问题. ...

  4. 由一个简单需求到Linux环境下的syslog、unix domain socket

    本文记录了因为一个简单的日志需求,继而对linux环境下syslog.rsyslog.unix domain socket的学习.本文关注使用层面,并不涉及rsyslog的实现原理,感兴趣的读者可以参 ...

  5. xgboost-python参数深入理解

    由于在工作中应用到xgboost做特征训练预测,因此需要深入理解xgboost训练过程中的参数的意思和影响. 通过search,https://www.analyticsvidhya.com/blog ...

  6. IIS7 / IIS7.5 URL 重写 HTTP 重定向到 HTTPS

    1.购买SSL证书,参考:http://www.cnblogs.com/yipu/p/3722135.html 2.IIS7 / IIS 7.5 下绑定 HTTPS 网站(购买Wildcard SSL ...

  7. UIImageView帧动画相关属性和方法

    @property(nonatomic,copy) NSArray *animationImages; 需要播放的序列帧图片数组(里面都是UIImage对象,会按顺序显示里面的图片) @propert ...

  8. 安装prometheus+grafana监控mysql redis kubernetes等

    1.prometheus安装 wget https://github.com/prometheus/prometheus/releases/download/v1.5.2/prometheus-1.5 ...

  9. shell是什么,各种shell的初步认识,适用于初学者

    shell是什么?有什么用处?怎么用?我相信,这是大部分人刚接触到shell都有过的疑问.下面小编为大家讲解一下自己的讲解,希望能对大家有所帮助. 什么是shell? shell就是系统内核的一层壳, ...

  10. flume日志采集框架使用

    flume日志采集框架使用 本次学习使用的全部过程均不在集群上,均在本机环境,供学习参考 先决条件: flume-ng-1.6.0-cdh5.8.3.tar  去cloudrea下载flume框架,笔 ...