gj3 Python数据模型(魔法函数)
3.1 什么是魔法函数
类里面,实现某些特性的内置函数,类似 def __xx__(): 的形式。 不要自己定义XX,并不是和某个类挂钩的
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list # 可迭代
def __getitem__(self, item):
return self.employee[item] # 长度,实现了len函数
def __len__(self):
return len(self.employee) company1 = Company(["tom", "bob", "jane"])
#
# company1= company[:2]
#
# print(len(company)) for em in company1:
print(em)
3.2 python的数据模型以及数据模型对python的影响
只要实现了对应的数据模型,就具有该模型的特性
3.3 魔法函数一览
3.3.1 非数学运算
字符串表示
__repr__ 开发模式下调用的
__str__ 对对象进行字符串格式化时调用
class Company(object):
def __init__(self, employee_list):
self.employee=employee_list
def __str__(self):
print("str called")
return",". join(self. employee)
def __repr__(self):
print("repr called")
return",". join(self. employee)
company=Company(["tom","bob","jane"])
company
# repr(company)
# company.__repr__()
# print(company) repr called
tom,bob,jane
Python数据模型(魔法函数)非数学运算
字符串表示
__repr__
__str__
集合、序列相关
__len__
__getitem__
__setitem__
__delitem__
__contains__
迭代相关
__iter__
__next__
可调用
__call__
with上下文管理器
__enter__
__exit__
数值转换
__abs__
__bool__
__int__
__float__
__hash__
__index__
元类相关
__new__
__init__
属性相关
__getattr__、 __setattr__
__getattribute__、setattribute__
__dir__
属性描述符
__get__、__set__、 __delete__
协程
__await__、__aiter__、__anext__、__aenter__、__aexit__
Python数据模型(魔法函数)--非数学运算
3.3.2 数学运算
一元运算符
__neg__(-)、__pos__(+)、__abs__
二元运算符
__lt__(<)、 __le__ <= 、 __eq__ == 、 __ne__ != 、 __gt__ > 、 __ge__ >=
算术运算符
__add__ + 、 __sub__ - 、 __mul__ * 、 __truediv__ / 、 __floordiv__ // 、 __ mod__ % 、 __divmod__ divmod() 、 __pow__ ** 或 pow() 、 __round__ round()
反向算术运算符
__radd__ 、 __rsub__ 、 __rmul__ 、 __rtruediv__ 、 __rfloordiv__ 、 __rmod__ 、 __rdivmod__ 、 __rpow__
增量赋值算术运算符
__iadd__ 、 __isub__ 、 __imul__ 、 __itruediv__ 、 __ifloordiv__ 、 __imod__ 、 __ipow__
位运算符
__invert__ ~ 、 __lshift__ << 、 __rshift__ >> 、 __and__ & 、 __or__ | 、 __ xor__ ^
反向位运算符
__rlshift__ 、 __rrshift__ 、 __rand__ 、 __rxor__ 、 __ror__
增量赋值位运算符
__ilshift__ 、 __irshift__ 、 __iand__ 、 __ixor__ 、 __ior__
数学运算
class Nums(object):
def __init__(self,num):
self.num=num
def __abs__(self):
return abs(self.num)
my_num=Nums(1)
abs(my_num)
1
class MyVector(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other_instance):
re_vector = MyVector(self.x + other_instance.x, self.y + other_instance.y)
return re_vector
def __str__(self):
return "x:{x},y:{y}".format(x=self.x, y=self.y)
first_vec = MyVector(1, 2)
second_vec = MyVector(2, 3)
print(first_vec + second_vec)
x:3,y:5
3.4 随便举个例子说明魔法函数的重要性(len函数)
len(set dict list) 会直接调用set dict list数据类型本身cpython的内置实现
在任何对象中都可以去实现魔法函数
只要实现了对应的魔法函数,就能实现Python某些数据类型的功能
gj3 Python数据模型(魔法函数)的更多相关文章
- Python的魔法函数系列 __getattrbute__和__getattr__
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys __metaclass__ = type """ _ ...
- python使用魔法函数创建可切片类型
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 可切片的对象 """ import nu ...
- 16个python常用魔法函数
==,is的使用 ·is是比较两个引用是否指向了同一个对象(引用比较). ·==是比较两个对象是否相等 1.__ init__(): 所有类的超类object,有一个默认包含pass的__ init ...
- python常用魔法函数
1.__init__(): 所有类的超类object,有一个默认包含pass的__init__()实现,这个函数会在对象初始化的时候调用,我们可以选择实现,也可以选择不实现,一般建议是实现的,不实现对 ...
- Python的魔法函数
概要 如何定义一个类 类里通常包含什么 各个部分解释 类是怎么来的 type和object的关系 判断对象的类型 上下文管理器 类结构 #!/usr/bin/env python # -*- codi ...
- Python的魔法函数之 - __len__,__getitem__,__setitem__,__delitem__
# 对象作为len()函数的参数是必须实现该方法 __len__ # 使用类似字典方式访问成员时必须实现 dic['pro_name'] __getitem__ # 使用类似字典方式设置成员时必须实现 ...
- Python魔法函数与两比特量子系统模拟
技术背景 本文主要涵盖两个领域的知识点:python的魔法函数和量子计算模拟,我们可以通过一个实际的案例来先审视一下这两个需求是如何被结合起来的. 量子计算模拟背景 ProjectQ是一个非常优雅的开 ...
- PythonI/O进阶学习笔记_2.魔法函数
前言: 本文一切观点和测试代码是在python3的基础上. Content: 1.什么是魔法函数,魔法函数__getitem__在python中应用. 2.python的数据模型和数据模型这种设计对p ...
- Python魔法函数
python中定义的以__开头和结尾的的函数.可以随意定制类的特性.魔法函数定义好之后一般不需要我们自己去调用,而是解释器会自动帮我们调用. __getitem__(self, item) 将类编程一 ...
随机推荐
- 机器学习入门-数据过采样(上采样)1. SMOTE
from imblearn.over_sampling import SMOTE # 导入 overstamp = SMOTE(random_state=0) # 对训练集的数据进行上采样,测试集的 ...
- Simple2D-15(音乐播放器)使用 glfw 库
glfw 是一个专门针对 OpenGL 的 C 语言库,它提供了一些渲染物体所需的最低限度的接口.它允许用户创建 OpenGL 上下文,定义窗口参数以及处理用户输入. 这次打算使用 GLFW 替代掉 ...
- jenkins 修改工作目录
修改Jenkins路径 Jenkins的默认安装路径是/var/lib/jenkins 现在由于这个根目录的磁盘太小,所以切换到/data 目录下. Jenkins目录.端口.工作目录等信息在/etc ...
- 系统批量运维管理器pexpect的使用
# pip install pexpect 或 # easy_install pexpect 1 #!/usr/bin/env python 2 import pexpect 3 child = pe ...
- mysql之explain
⊙ 使用EXPLAIN语法检查查询执行计划 ◎ 查看索引的使用情况 ◎ 查看行扫描情况 ⊙ 避免使用SELECT * ◎ 这会导致表的全扫描 ◎ 网络带宽会被浪费 话说工欲善其 ...
- avalon的常见问题
随着avalon的普及,越来越多人加入avalon的大家庭.随之而来的是各种问题.本文在这里统一解答一下. 使用avalon基本上有几个方针要坚持 数据必须先定义后使用,只能VM中定义,不能V中定义. ...
- mysql 建库建表建用户
1.创建数据库 create database school; 2.使用数据库 Use school; 3.创建用户 create user jame@localhost identified by ...
- 神经网络中embedding层作用——本质就是word2vec,数据降维,同时可以很方便计算同义词(各个word之间的距离),底层实现是2-gram(词频)+神经网络
Embedding tflearn.layers.embedding_ops.embedding (incoming, input_dim, output_dim, validate_indices= ...
- ECMAScript5之JSON对象属性的遍历顺序
测试浏览器 Chrome.Safari 一 键可以用parseInt解析成整数的,按数值升序顺序. var intObj = { '3.3' : 3.3, '2' : 222, '1' :111 } ...
- Writing A Better JavaScript Library For The DOM 阅读记录
原文地址:http://coding.smashingmagazine.com/2014/01/13/better-javascript-library-for-the-dom/ 主要观点: live ...