Pthon面向对象-补充知识
Pthon面向对象-补充知识
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.tracemalloc
标准库tracemalloc,可以统计内存使用情况,通过下面的案例可以看出内存使用上字典还是较为占用空间的。
#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie import tracemalloc tracemalloc.start() #开始跟踪内存分配 d = [dict(zip("xy",(,))) for i in range()] #237M t = [tuple(zip("xy",(,))) for i in range()] #191M
snapshot = tracemalloc.take_snapshot() #快照,当前内存分配 top_stats = snapshot.statistics("lineno") #快照对象的统计 for stat in top_stats:
print(stat) #以上代码执行结果如下:
D:/Language/Python/Code/Devops/Python基础/.面向对象编程/魔术方法/.补充知识.py:: size= MiB, count=, average= B
D:/Language/Python/Code/Devops/Python基础/.面向对象编程/魔术方法/.补充知识.py:: size= MiB, count=, average= B
D:/Language/Python/Code/Devops/Python基础/.面向对象编程/魔术方法/.补充知识.py:: size= B, count=, average= B
D:\Language\Python\interpreter\Python37\lib\tracemalloc.py:: size= B, count=, average= B
二.__slots__
应用场景:
使用需要构建在数百万以上众多对象,且内存容量较为紧张,实例的属性简单,固定且不用动态增加的场景。
可以使用tracemalloc看看内存使用的差异。建议使用stats = snapshot.statistics("filename")查看总内存使用。
#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie class A:
x = 100 """
"__slots__"魔术方法会告诉解释器,实例的属性都叫上面,一般来说,既然要节约内存,最好还是使用元组比较好。
一旦提供了"__slots__",就阻止实例产生"__dict__"来保存实例的属性。
"""
__slots__ = ("y","z") def __init__(self):
self.y = 20
self.z = 30 def show(self):
print(self.x,self.y) class B(A): #B类继承自A类
pass a = A()
a.show()
# a.name = "tom" #会抛异常"AttributeError: 'A' object has no attribute 'name'",说明实例不可以动态增加属性了,因为属性已经被"__slots__"提前定义好啦! A.name = "Tom" #这是可以的,因为这个是类属性,说明"__slots__"只能限制当前实例而不能限制当前类 print(A.name)
print("A",A.__dict__)
print("B",B().__dict__) #可以访问B类实例的"__dict__"属性,说明"__slots__"不影响类实例,不会继续下去,除非子类里面自己也定义了"__slots__"
# print(a.__dict__) #抛异常"AttributeError: 'A' object has no attribute '__dict__'",一旦提供了"__slots__",就阻止实例产生"__dict__"来保存实例的属性。
print(a.__slots__) #以上代码执行结果如下:
100 20
Tom
A {'__module__': '__main__', 'x': 100, '__slots__': ('y', 'z'), '__init__': <function A.__init__ at 0x00000157A5B05678>, 'show': <function A.show at 0x00000157A5B051F8>, 'y': <member 'y' of 'A' objects>, 'z': <member 'z' of 'A' objects>, '__doc__': None, 'name': 'Tom'}
B {}
('y', 'z')
三.未实现和未实现异常
#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie print(type(NotImplemented))
print(type(NotImplementedError)) print(NotImplemented) #是个值,单值,是"NotImplementedType"类的实例 raise NotImplementedError #是类型,是异常类,返回type #以上代码执行结果如下:
<class 'NotImplementedType'>
<class 'type'>
NotImplemented
Traceback (most recent call last):
File "D:/Language/Python/Code/Devops/Python基础/07.面向对象编程/魔术方法/13.补充知识.py", line 12, in <module>
raise NotImplementedError #是类型,是异常类,返回type
NotImplementedError
四.运算符重载中的反向方法
#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie class A:
def __init__(self,x):
self.x = x def __add__(self, other):
print(self,"add")
return self.x + other.x def __iadd__(self, other):
print(self,"iadd")
return A(self.x + other.x) def __radd__(self, other):
print(self,"radd")
return self.x + other.x class B:
def __init__(self,x):
self.x = x """
如果不实现"__add__"方法,其实B类也等价于下面注释的代码
"""
# def __add__(self, other):
# if isinstance(other,type(self)):
# return self.x + other.x
# else:
# return NotImplemented a = A(10)
b = A(20)
print(a,b)
print(a + b) #调用"__add__"方法
print(b + a)
b += a #调用"_iadd__"方法
a += b #同上 c = B(30)
print(a + c)
print(c + a) #这里的c是类B的实例,但是类B没有实现"__add__"方法,就去找a的"_radd__"方法
# print(a + "abc") #报错"AttributeError: 'str' object has no attribute 'x'",字符串实现了"__add__"方法,不过默认是处理不了和其它类型的加法,就返回"NotImplemented"
# print(1 + a) #报错"AttributeError: 'int' object has no attribute 'x'",整型也实现了"__add__"方法的,不过这个方法对于这种加法的返回值是"NotImplemented",解释器发现在这个值,就会发起第二操作对象的"__radd__"方法的调用。 #以上代码执行结果如下:
<__main__.A object at 0x000001DFBE585908> <__main__.A object at 0x000001DFBE585988>
<__main__.A object at 0x000001DFBE585908> add
30
<__main__.A object at 0x000001DFBE585988> add
30
<__main__.A object at 0x000001DFBE585988> iadd
<__main__.A object at 0x000001DFBE585908> iadd
<__main__.A object at 0x000001DFBE585A48> add
70
<__main__.A object at 0x000001DFBE585A48> radd
70
五.仅位置参数
#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie """
2019年10月14日,发布了Python3.8.0,提供了仅位置参数(Positional-only arguments)。
""" def add(x, y=5, /, z=6):
print(x + y + z) add(1, 2, 3)
add(1, y=2, z=3)
add(x=1, y=2, z=3)
add(1, 3, z=5)
六.Python的对象模型
在Python中,任何对象都有类型,可以使用type()或者 __class__ 查看。
但是类型也是对象即类对象,它也有自己的类型。
所有新类型的缺省类型是type(可以使用元类来改变) 特殊类型type是所有对象的缺省类型,也包括type自己。但它又是一个对象,因此从object继承特殊类型object是继承树的顶层,它是python所有类型的最终基类
也就是说,继承都来自object,类型都看type。type也是对象继承自object,object也有类型是type。 这俩又特殊,type类型是它自己,object没有基类。
七.断言语法
#!/usr/bin/env python
#_*_conding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie a = 100 assert a > 80,"对变量a进行断言,即如果a大于80则条件成立不做任何处理,否则抛出异常" print("{0} 我是分隔符 {0}".format("*" * 30)) assert a < 100,"对变量a进行断言,即如果a小于100则条件成立不做任何处理,否则抛出异常"
Pthon面向对象-补充知识的更多相关文章
- 面向对象 - 1.面向过程/2.面向对象/3.如何使用类/4.__init__方法/5.属性查找/6.补充知识/7.可扩展性高
编程范式(流派): 面向对象编程,面向过程编程 各有用处!! 编程:语法+数据结构(list dict)+算法(逻辑)-----------------------------------1.面向过程 ...
- 031医疗项目-模块三:药品供应商目录模块——供货商药品目录查询功能----------sql补充知识
这个补充知识有一个点很有必要,视屏上的老师提出一点: 内链接关联查询: 如果表A和表B有一个外键关联 ,可以通过外键进行内链接查询 select dictinfo.*, dicttype.typena ...
- Python 面向对象基础知识
面向对象基础知识 1.什么是面向对象编程? - 以前使用函数 - 类 + 对象 2.什么是类什么是对象,又有什么关系? class 类: def 函数1(): pass def 函数2(): pass ...
- JavaScript 面向对象开发知识基础总结
JavaScript 面向对象开发知识基础总结 最近看了两本书,书中有些内容对自己还是很新的,有些内容是之前自己理解不够深的,所以拿出来总结一下,这两本书的名字如下: JavaScript 面向对象精 ...
- freeMarker(五)——模板开发指南补充知识
学习笔记,选自freeMarker中文文档,译自 Email: ddekany at users.sourceforge.net 模板开发指南补充知识 1. 自定义指令 自定义指令可以使用 macro ...
- sql系列(基础篇)-前言 课前补充知识
前言 课前补充知识 Number(p,s) Number(p,s):数字类型,p 表示数字的有效长度(从数字的左边第 1 位不为 0 的開始算起,直到最右边的长度.取值范围 0~38 位),s 表示数 ...
- 10.11 android输入系统_补充知识_activity_window_decor_view关系
android里:1个application, 有1个或多个activity(比如支付宝有:首页.财富.口碑.朋友.我的,这些就是activity)1个activity, 有1个window(每个ac ...
- 8.6 day27 网络编程 osi七层协议 Time模块补充知识 TCP协议
Time模块补充知识 date和datetime区别是什么? date 就是年月日 datetime就是年月时时分秒 以下代码为什么会报错? import json from datetime imp ...
- 范仁义html+css课程---11、html补充知识
范仁义html+css课程---11.html补充知识 一.总结 一句话总结: 小于号(<):< 大于号(>):> 空格: 二.html 字符实体 1.小于号(<)和大 ...
随机推荐
- Docker使用 - 镜像
获取镜像 命令:docker pull [选项] 镜像名 可通过 ”docker pull --help“ 命令来查看有哪些选项 docker pull training/webapp # ...
- Swift编码总结9
1.Swift限制textField输入位数为10位: func textField(_ textField: UITextField, shouldChangeCharactersIn range: ...
- IntelliJ Idea 常用10款插件(提高开发效率)
出自:https://blog.csdn.net/weixin_41846320/article/details/82697818 插件安装方式: 1.Background Image Plus 这款 ...
- [Mobi] cordova requirements,Exception in thread "main" java.lang.NoClassDefFoundError
Cordova App Preparation https://quasar.dev/quasar-cli/developing-cordova-apps/preparation $ cordova ...
- Navicat连接Mysql8.0.11出现1251错误
# 登录mysql mysql -u root -p # 修改加密规则 mysql> ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_pas ...
- Redis Sentinel 高可用部署实践集群
一.Redis Sentinel 介绍 1.Sentinel 数据库环境搭建,从单机版到主备.再到多数据库集群,我们需要一个高可用的监控:比如Mysql中,我们可能会采用MHA来搭建我们 ...
- Kubernetes+Istio
Kubernetes+Istio 微服务.SpringCloud.k8s.Istio杂谈 一.微服务与SOA “微服务”是一个名词,没有这个名词之前也有“微服务”,一个朗朗上口的名词能让大家产 ...
- oracle 通用事务使用
private void dothing() { OracleConnection con = DBHelperOracle.init(); OracleTransaction tran = con. ...
- [转帖]VirtualBox 网络模式
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://xiaoyu.blog.csdn.net/article/detail ...
- Mybatis自动生成代码工具
项目结构如下 一:在POM中添加mybatis-generator-maven-plugin 插件 <plugins> <plugin> <groupId>org. ...