python item repr doc format slots doc module class 析构 call 描述符
1.item
# __getitem__ __setitem__ __delitem__ obj['属性']操作触发 class Foo:
def __getitem__(self, item):
return self.__dict__[item] def __setitem__(self, key, value):
self.__dict__[key] = value def __delitem__(self, key):
self.__dict__.pop(key) f = Foo()
f.name = 'zq'
f.age =
print(f.__dict__) del f.name
print(f.__dict__) print(f.age)
2.str repr
class Foo:
def __init__(self,name,age):
self.name = name
self.age = age def __str__(self):
return "定制__str__ %s %s" %(self.name,self.age) def __repr__(self):
return "定制的__repr__ 替换__str__" f = Foo("zhangsan","") # 改变对象的字符串显示
# __str__
# __repr__ 在解释器中触发 当和str同时存在执行str,当str不存在,执行repr,是str的替代者
# str(f) > f.__str__()> "定制__str__"
print(f) # 定制__str__ zhangsan 12
3.format定制
# 自定制 format
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day def __format__(self, format_spec=""):
return "{0.year}{format_spec}{0.month}{format_spec}{0.day}".format(self, format_spec=format_spec) d1 = Date('', '', '')
print(format(d1)) #
print(format(d1, ':')) # 2018:12:12
4.slot 类变量
# __slots__ 是一个类变量 可以是list tunple iter...
# 减少内存使用 取代__dict__的属性 不再有__dict__
# 1.限制创建属性
class Foo:
__slots__ = ['name', 'age'] # 类似属性字典 定义字典中key {'name':None,'age':None} f1 = Foo()
f1.name = 'zhangsan'
f1.age = 100
# print(f1.__dict__) # AttributeError: 'Foo' object has no attribute '__dict__'
print(f1.__slots__) # ['name', 'age']
print(f1.name, f1.age)
# f1.gender = 'man' # AttributeError: 'Foo' object has no attribute 'gender'
5.doc
# __doc__ 文档注释 改属性不可被继承
class Foo:
'''
我是Foo文档信息
'''
pass class A(Foo):
'''
我是A文档信息
'''
pass print(Foo.__doc__) # 我是Foo文档信息
print(A.__doc__) # 我是A文档信息
6.module class
# __module__ 查看由那个module产生
# __class__ 查看由那个类产生
import c
c = c.c()
print(c.name)
print(c.__module__)
print(c.__class__)
7.析构方法 __del__ 当对象在内存中被释放时,自动触发执行
# __del__ 析构函数 删除实例才触发该函数
class Foo:
def __init__(self, name):
self.name = name def __del__(self):
print("__del__ 实例") f1 = Foo('zhangsan')
del f1.name # 先删除实例的属性 再执行下面语句 然后删除实例 执行析构函数
print("--------->")
8.call方法
# call 对象后面加(),触发执行
# call 类()执行 会触发__call__ 函数 Foo()
class Foo:
def __call__(self, *args, **kwargs):
print("触发实例 obj()") f1 = Foo()
f1()
Foo()
9.迭代器协议 next iter
# 迭代器协议:对象必须有一个next方法,执行一次返回迭代下一项,直到Stopiteration,
# __iter___ 把一个对象变成可迭代对象
class Foo:
def __init__(self, age):
self.age = age def __iter__(self):
return self def __next__(self):
if self.age == 197:
raise StopIteration("end")
self.age += 1
return self.age f1 = Foo(195)
print(f1.__next__())
print(f1.__next__())
# print(f1.__next__()) for i in f1: # for循环调用f1中的iter方法变成可迭代对象 再执行next方法 iter(f1)==f1.__iter__()
print(i) # 斐波那契数列
class Fib:
def __init__(self, num):
self._x = 1
self._y = 1
self.num = num def __iter__(self):
return self def __next__(self):
self._x, self._y = self._y, self._x + self._y
if self._x > self.num:
raise StopIteration("结束")
return self._x def show_fib(self):
l = []
for i in self:
l.append(i)
return l #求1000内的数
f1 = Fib(100000)
print(f1.show_fib())
10.描述符
描述符是什么:描述符本质就是一个新式类,在这个新式类中,至少实现了__get__(),__set__(),__delete__()中的一个,这也被称为描述符协议
__get__():调用一个属性时,触发
__set__():为一个属性赋值时,触发
__delete__():采用del删除属性时,触发
#描述符Str
class Str:
def __get__(self, instance, owner):
print('Str调用')
def __set__(self, instance, value):
print('Str设置...')
def __delete__(self, instance):
print('Str删除...') #描述符Int
class Int:
def __get__(self, instance, owner):
print('Int调用')
def __set__(self, instance, value):
print('Int设置...')
def __delete__(self, instance):
print('Int删除...') class People:
name=Str()
age=Int()
def __init__(self,name,age): #name被Str类代理,age被Int类代理,
self.name=name
self.age=age #何地?:定义成另外一个类的类属性 #何时?:且看下列演示 p1=People('alex',18) #描述符Str的使用
p1.name
p1.name='egon'
del p1.name #描述符Int的使用
p1.age
p1.age=18
del p1.age #我们来瞅瞅到底发生了什么
print(p1.__dict__)
print(People.__dict__) #补充
print(type(p1) == People) #type(obj)其实是查看obj是由哪个类实例化来的
print(type(p1).__dict__ == People.__dict__) 描述符应用之何时?何地?
注意事项:
一 描述符本身应该定义成新式类,被代理的类也应该是新式类
二 必须把描述符定义成这个类的类属性,不能为定义到构造函数中
三 要严格遵循该优先级,优先级由高到底分别是
1.类属性
2.数据描述符
3.实例属性
4.非数据描述符
5.找不到的属性触发__getattr__()
11.开发规范
# 软件开发规范 范例
'''
bin 脚本文件
start.py 启动文件 conf
settings.py 配置文件 db 用户数据
admin
classes
teacher
course
cource_to_school
student lib 公共类库
commons.py log 日志信息 src或core 核心文件 #导入模块
# BASER_DIR
import sys, os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
参考:http://www.cnblogs.com/linhaifeng/articles/6204014.html
python item repr doc format slots doc module class 析构 call 描述符的更多相关文章
- 如何正确地使用Python的属性和描述符
关于@property装饰器 在Python中我们使用@property装饰器来把对函数的调用伪装成对属性的访问. 那么为什么要这样做呢?因为@property让我们将自定义的代码同变量的访问/设定联 ...
- Python中属性和描述符的简单使用
Python的描述符和属性是接触到Python核心编程中一个比较难以理解的内容,自己在学习的过程中也遇到过很多的疑惑,通过google和阅读源码,现将自己的理解和心得记录下来,也为正在为了该问题苦恼的 ...
- Python 中的属性访问与描述符
在Python中,对于一个对象的属性访问,我们一般采用的是点(.)属性运算符进行操作.例如,有一个类实例对象foo,它有一个name属性,那便可以使用foo.name对此属性进行访问.一般而言,点(. ...
- Python中的属性访问与描述符
Python中的属性访问与描述符 请给作者点赞--> 原文链接 在Python中,对于一个对象的属性访问,我们一般采用的是点(.)属性运算符进行操作.例如,有一个类实例对象foo,它有一个nam ...
- python高级编程之描述符与属性02
# -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' #元描述符 #特点是:使用宿主类的一个或者多个方法来执行一个任务,可 ...
- Python描述符 (descriptor) 详解
1.什么是描述符? python描述符是一个“绑定行为”的对象属性,在描述符协议中,它可以通过方法重写属性的访问.这些方法有 __get__(), __set__(), 和__delete__().如 ...
- Python强大的格式化format
原文地址:http://www.jb51.net/article/63672.htm 自python2.6开始,新增了一种格式化字符串的函数str.format(),可谓威力十足.那么,他跟之前的%型 ...
- (转)Python 字符串格式化 str.format 简介
原文:https://www.cnblogs.com/wilber2013/p/4641616.html http://blog.konghy.cn/2016/11/25/python-str-for ...
- python代码迷之错误(ModuleNotFoundError: No module named 'caffe.proto')
1.pandas.read_csv book[n]下的print(n) 总图片数是少一张的,print(n)发现也是少了一个序号 仔细查找后发现缺少99号,即最后一张图片没有被读取.print(m)时 ...
随机推荐
- C. Edgy Trees Codeforces Round #548 (Div. 2) 【连通块】
一.题面 here 二.分析 这题刚开始没读懂题意,后来明白了,原来就是一个数连通块里点数的问题.首先在建图的时候,只考虑红色路径上的点.为什么呢,因为为了不走红色的快,那么我们可以反着想只走红色的路 ...
- [Re:从零开始的分布式] 0.x——Reids实现分布式锁
上节提到了,分布式锁通常应满足如下要求,互斥性.高可用.高效率.可重入.锁失效这五个基本原则.由于Redis自身“快”的特点,所以高效率可以看作满足. 下文在单机情况下与多机情况下,对利用Redis实 ...
- [转] Spark sql 内置配置(V2.2)
[From] https://blog.csdn.net/u010990043/article/details/82842995 最近整理了一下spark SQL内置配.加粗配置项是对sparkSQL ...
- 剑指offer——面试题26:判断二叉树B是否为二叉树A的子结构
#include"iostream" #include"stdio.h" #include"math.h" using namespace ...
- hibernate3.3.2搭建log4j日志环境
日志的框架有很多,hibernate3.3.2用的是slf4j,slf4j简单理解为一个接口,标准.具体的实现可以是不同的实现(如slf4j自己的实现,log4j等).slf就像JDBC,JPA.自己 ...
- Git提交项目到GitHub
一.GitHub新建项目 1.进入Github首页,点击New repository新建一个项目 2.填写相应信息后点击create即可 Repository name: 仓库名称 Descripti ...
- Capture Conversion解读
Let G name a generic type declaration with n type parameters A1,...,An with corresponding bounds U1, ...
- ZOJ 2971 Give Me the Number
Give Me the Number Numbers in English are written down in the following way (only numbers less than ...
- Windows下编程--模拟时钟的实现
windows下编程--模拟时钟的实现: 主要可以分为几个步骤: (1) 编写按键事件处理(启动和停止时钟) (2) 编写时钟事件处理,调用显示时钟函数 (3) 编写显示时钟函数,要调用显 ...
- IOS Core Image之二
在上篇博客IOS Core Image之一中了解了下CIImage.CIFilter.CIContext三个类的使用,这篇了解下滤镜链(多滤镜)和人脸检测(不是人脸识别). 一.多滤镜 1.有些效果不 ...