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) 将类编程一 ...
随机推荐
- libcurl 不支持https访问
项目中使用libcurl 访问https的时候会报错,比如:“Unsupported protocol” 或者:“Protocol https not supported or disabled in ...
- 一个完整的Oracle建表的例子
建表一般来说是个挺简单的事情,但是Oracle的建表语句有很多可选的参数,有些我们可能平时不太用,用的时候又不知道怎么用,这里就写一个较完整的建表的例子: [sql] CREATE TABLE ban ...
- node系列:全局与本地
查看:默认和当前的 全局与本地 全局路径:npm config get prefix 本地路径:npm config get cache 修改 修改就会创建对应目录(文件夹) 修改本地路径:npm c ...
- 自定义worker的方法,及一例
自定义的worker用于处理各种特殊需求. 有网友想用html_json提取雪球网(https://xueqiu.com/)的数据,可是雪球网用了反爬虫技术,网站要求有cookies才能访问到json ...
- 迭代删除元素 并发bug 低级错误
方法一:HashMap<String, Integer> myHashMap = new HashMap<>();myHashMap.put("1", 1) ...
- nginx的Mainline version、Stable version、Legacy version
Nginx官网提供了三个类型的版本Mainline version:Mainline 是 Nginx 目前主力在做的版本,可以说是开发版Stable version:最新稳定版,生产环境上建议使用的版 ...
- 通过jquery,从json中读取数据追加到html中
1.下载安装jquery 可通过下面的方法引入在线版本的js: <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jque ...
- Python的logging,记录log的包
最近在做自动化测试时,想给他加上日志,所以用到logging的模块,以下是python增加log的几种方式 一.python代码配置方式(当然还有一种是可以多模块通用的一个python代码设置,这个网 ...
- oracle查询锁表
select b.username,b.sid,b.serial#,logon_time from v$locked_object a,v$session b where a.session_id = ...
- Ajax的get方式传值 避免& 与= 号
js代码 例如: var name = $("#name”).value;//为a&b=7 name=encodeURLComponent(name); 可以将a&b=7转化 ...