符合Python风格的对象
array和bytes的转换
- 每个array必须有一个type_code,以此为依据解析底层字节序列
- array有一个frombytes方法,可以把字节序列按type_code转换成Array
- bytes构造函数接受一个可迭代对象作为参数,它依次遍历可迭代对象,将每个元素按其本身的数据类型拆成字节
from array import array
def create_bytes():
type_code = 'f'
# ord函数返回字符的编码
print('type_code:',ord(type_code))
ar = array(type_code,[0.19,0.23])
# bytes构造函数接受一个可迭代对象作为参数
# 它依次遍历可迭代对象,将每个元素拆成字节
# type_code1个字节,float4个字节,一共9个字节
by = bytes([ord(type_code)]) + bytes(ar)
print('bytes(len:%d):' % len(by), by)
return by
def from_bytes(by):
# 将第一个字节转换为字符
type_code = chr(by[0])
# 以后的每4个字节转换为一个float
# 先用type_code构造一个Array
arr = array(type_code)
# 再把字节序列按type_code转换成Array
arr.frombytes(by[1:])
print(arr)
bytes = create_bytes()
from_bytes(bytes)
输出:
type_code: 102
bytes(len:9): b'f\\\x8fB>\x1f\x85k>'
array('f', [0.1899999976158142, 0.23000000417232513])
classmethod和staticmethod
class Demo:
@classmethod
def klassmethod(*args):
print(args)
@staticmethod
def statmethod(*args):
print(args)
# classmethod自动将类作为第一个参数传入
Demo.klassmethod()
Demo.klassmethod('param')
# staticmethod只是定义在类中的一个普通方法
Demo.statmethod()
Demo.statmethod('param')
输出:
(<class '__main__.Demo'>,)
(<class '__main__.Demo'>, 'param')
()
('param',)
对象散列相关方法
- 首先要保证对象不可变
- 其次要实现hash和eq方法
class Vector2d:
def __init__(self,_x,_y):
self._x = float(_x)
self._y = float(_y)
def __iter__(self):
return (item for item in (self.x,self.y))
# 用propery装饰器设置只读属性,保持对象的不可变
@property
def x(self):
return self._x
@property
def y(self):
return self._y
# 使对象可散列
def __hash__(self):
return hash(self.x) ^ hash(self.y)
# 可散列的同时,还要实现相等方法
def __eq__(self, other):
return self.x == other.x and self.y == other.y
v1 = Vector2d(3,4)
v2 = Vector2d(3,4)
print(hash(v1),hash(v2),v1==v2)
输出:
7 7 True
Python的私有属性
class Dog:
def __init__(self,name):
# 如果以__var的形式命名实例属性,Python会把属性名存入实例的__dict__属性中
# 而且会在前面加上一个下划线和类名
self.__name = name
dog = Dog('Bob')
print(dog.__dict__)
# 'Dog' object has no attribute '__name'
# print(dog.__name)
print(dog._Dog__name)
输出:
{'_Dog__name': 'Bob'}
Bob
使用__slots__类属性
- 用法
- 创建__slots__类属性,把值设置为一个属性名称(字符串)构成的可迭代对象
- 好处:
- 可以避免使用消耗内存的__dict__属性,从而节约内存
- 不允许实例动态创建其他的属性
class Vector2d:
__slots__ = ('_x','_y')
def __init__(self,_x,_y):
self._x = float(_x)
self._y = float(_y)
v2d = Vector2d(1,2)
# 'Vector2d' object has no attribute '__dict__'
# print(v2d.__dict__)
# 'Vector2d' object has no attribute 'z'
# v2d.z = 'z'
- 注意点
- 如果把 '__dict__' 这个名称添加到__slots__中,实例会在元组中保存各个实例的属性,此外还支持动态创建属性
- 为了让对象支持弱引用,需要再__slots__中放__weakref__属性
- 每个子类要定义自己的__slots__属性,继承无效
class Vector2d:
__slots__ = ('_x','_y','__dict__')
def __init__(self,_x,_y):
self._x = float(_x)
self._y = float(_y)
v2d = Vector2d(1,2)
v2d.z = 'z'
print(v2d.__dict__)
输出:
{'z': 'z'}
符合Python风格的对象的更多相关文章
- 第9章 符合Python风格的对象
#<流畅的Python>读书笔记 # 第9章 符合Python风格的对象 # 本章包含以下话题: # 支持用于生成对象其他表示形式的内置函数(如repr().bytes(),等等) # 使 ...
- python 符合Python风格的对象
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 25.0px Helvetica } 对象表示形式 每门面向对象的语言至少都有一种获取对象的字符串表示形式的 ...
- 流畅的python第九章符合Python风格的对象学习记录
对象表示形式 每门面向对象的语言至少都有一种获取对象的字符串表示形式的标准方式.Python提供了两种方式 repr()便于开发者理解的方式返回对象的字符串表示形式 str()便于用户理解的方式返回对 ...
- 流畅的python 符合python风格的对象
对象表示形式 每门面向对象的语言至少都有一种获取对象的字符串表示形式的标准方式.Python 提供了两种方式. repr() 以便于开发者理解的方式返回对象的字符串表示形式.str() 以便于用户理解 ...
- 流畅的python学习笔记:第九章:符合python风格的对象
首先来看下对象的表现形式: class People(): def __init__(self,name,age): self.name=name self.a ...
- Fluent_Python_Part4面向对象,09-pythonic-obj,Python风格的对象
第四部分第9章,Python风格的对象 这一章接第1章,说明常见的特殊方法实现. 本章包括以下话题: 支持用于生成对象其它表示形式的内置函数(如repr().bytes(),等等) 使用一个类方法实现 ...
- 第8.25节 Python风格的__getattribute__属性访问方法语法释义及使用
一. 引言 在<第8.13节 Python类中内置方法__repr__详解>老猿介绍了在命令行方式直接输入"对象"就可以调用repr内置函数或__repr__方法查看对 ...
- Python风格规范
Python风格规范 分号 Tip 不要在行尾加分号, 也不要用分号将两条命令放在同一行. 行长度 Tip 每行不超过80个字符 例外: 长的导入模块语句 注释里的URL 不要使用反斜杠连接行. Py ...
- PYTHON风格规范-Google 开源项目风格指南
Python风格规范 分号 Tip 不要在行尾加分号, 也不要用分号将两条命令放在同一行. 行长度 Tip 每行不超过80个字符 例外: 长的导入模块语句 注释里的URL 不要使用反斜杠连接行. Py ...
随机推荐
- Liunx 解压篇
解压完 却不知道到哪里去了这时
- SQL获取当前日期的年、月、日、时、分、秒数据
SQL Server中获取当前日期的年.月.日.时.分.秒数据: SELECT GETDATE() as '当前日期',DateName(year,GetDate()) as '年',DateName ...
- Java开发环境之------MyEclipse快捷键和排除错误第一选择ctrl+1(***重点***:ctrl+1,快速修复---有点像vs中的快速using
using Java开发环境之------MyEclipse快捷键和排除错误第一选择ctrl+1(***重点***:ctrl+1,快速修复---有点像vs中的快速using 2015-06-29 浏览 ...
- 12 Overlap Graphs
Problem A graph whose nodes have all been labeled can be represented by an adjacency list, in which ...
- Kubernetes 中的pv和pvc
原文地址:http://www.cnblogs.com/leidaxia/p/6485646.html 持久卷 PersistentVolumes 本文描述了 Kubernetes 中的 Persis ...
- UVaLive 4043 Ants (最佳完美匹配)
题意:给定 n 个只蚂蚁和 n 棵树的坐标,问怎么匹配使得每个蚂蚁到树的连线不相交. 析:可以把蚂蚁和树分别看成是两类,那么就是一个完全匹配就好,但是要他们的连线不相交,那么就得考虑,最佳完美匹配是可 ...
- Shell编程-01-Shell脚本初步入门
目录 什么是Shell 什么是Shell脚本 Shell脚本语言的种类 常用操作系统默认Shell Shell 脚本的建立和执行 脚本规范 什么是Shell 简单来说Shell其实就是一个命令 ...
- css选择器与DOM'匹配的关系
一道面试题 css 选择器匹配时,只考察是否包含有对应的class,而与class的顺序无关 而css的定义是后面的覆盖前面的定义 原理:http://www.w3.org/html/ig/zh/wi ...
- .NET框架源码解读之准备CLR源码阅读环境
微软发布了CLR 2.0的源码,这个源码是可以直接在freebsd和windows环境下编译及运行的,请在微软shared source cli(http://www.microsoft.com/en ...
- 调用kylin的restAPI接口构建cube
调用kylin的restAPI接口构建cube 参考:http://kylin.apache.org/docs/howto/howto_build_cube_with_restapi.html 1. ...