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) 将类编程一 ...
随机推荐
- padding 扩大边距 margin-top 与页面顶部的距离 hover鼠标移动到上面出现背景色CSS
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Java Collection.sort 排序升序, 降序问题
不多说,记住2点, 直接上代码(下面是降序): package mall; import java.util.ArrayList; import java.util.Collections; impo ...
- S+ hidden tray with window start
官方论坛上有个帖子给出了答案: I forgot that this is supported in the code, but it requires a little editing of the ...
- UI5-文档-4.1-Hello World!
如你所知,SAPUI5是关于HTML5的.让我们开始构建第一个仅使用HTML的“Hello World”. Preview 浏览器显示文本“Hello World” Coding 你可以在此查看和下载 ...
- scala sparseVetor, SprseMatrix 实现
def rand(seed:Int):Double={ val rand=new Random(seed) rand.nextDouble()} def rand2(size:Int,seed:Int ...
- (转)新手C#SQL语句的学习2018.08.13
1.创建数据库(create) CREATE DATABASE database-name 2.删除数据库(drop) drop database dbname 3.备份数据库 --- 创建 备份数据 ...
- linux 下 安装nginx及压力测试
linux 编译安装nginx,配置自启动脚本 下载nginx: wget http://nginx.org/download/nginx-1.8.0.tar.gz下载openssl : wget h ...
- github page更新后不生效
昨晚在本地git仓库修改了页面内容后,git push上去,到页面去刷新发现,并没有改变.本来还想着是需要点时间来更新,就再等等. 没想到过了十几分钟后,还是没有更新. 然后同时习惯性地打开了邮箱,发 ...
- for循环语句个人小结
重新看了一下光盘上的用for循环写一个菱形的答案,发现了其实有几点是可以灵活运用的: 1,当定义行数的时候,也可以用相等的间断的数字隔开,比如 for(int a = 5; a >= 1; a- ...
- ThreadPoolExecutor的execute源码分析
上一篇文章指出,ThreadPoolExecutor执行的步骤如下: 向线程池中添加任务,当任务数量少于corePoolSize时,会自动创建thead来处理这些任务: 当添加任务数大于corePoo ...