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) 将类编程一 ...
随机推荐
- MySQL 获取最后插入的ID LAST_INSERT_ID用法
LAST_INSERT_ID() 自动返回最后一个INSERT或 UPDATE 查询中 AUTO_INCREMENT列设置的第一个表发生的值. MySQL的LAST_INSERT_ID的注意事项: 第 ...
- Spring boot 执行jar文件 方式
项目jar包名wxo.jar 清理,打包,跳过测试(不测试) mvn clean package -Dmaven.test.skip=true 后台执行(默认环境) nohup java -jar w ...
- jsfl 改变舞台宽高
fl.getDocumentDOM().height= 680; fl.getDocumentDOM().width= 550;
- as3 air 保存文本内容的换行
private function newData() { var str:String="<root>"; for(var i in charCode_arr) { s ...
- const对象,指向const对象的指针 和 const 指针
const对象: const对象声明时必须赋初值,该值在编译阶段确定,不可在程序中修改. const修饰符既可放在类型名前也可放在类型名后,通常放在类型名前.不过放在类型名后易于理解. const i ...
- centor os 安装nginx
安装nginx和health check wget http://nginx.org/download/nginx-1.4.5.tar.gz git clone https://github.com/ ...
- 安装和使用iOS的包管理工具CocoaPods
CocoaPods是ruby实现的,需要用ruby进行安装,mac自带ruby,如果没有ruby的需要先安装ruby. 安装CocoaPods命令 安装CocoaPods命令:sudo gem i ...
- Xcrysden-2
XCrySDen -- (X-Window) CRYstalline Structures and DENsities Introduction to use. XCrySDen is a cryst ...
- Extjs面板和布局初探
面板相当于一张干净的白纸,如果直接在上面添加内容,将很难控制面板中内容的显示位置,面板元素越多就越显得凌乱,所以需要在面板上划分不同的区域,将面板内容展示到希望的位置上.ExtJS通过提供多种布局类来 ...
- swift textfield 和 textview 实时获取 输入内容
textfield : func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replac ...