惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

AI
AI
WordPress大学
WordPress大学
博客园 - 聂微东
Hugging Face - Blog
Hugging Face - Blog
小众软件
小众软件
V
V2EX
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
V
Visual Studio Blog
The GitHub Blog
The GitHub Blog
IT之家
IT之家
D
Docker
M
MIT News - Artificial intelligence
D
DataBreaches.Net
博客园 - 三生石上(FineUI控件)
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
博客园_首页
Y
Y Combinator Blog
F
Full Disclosure
Microsoft Security Blog
Microsoft Security Blog
月光博客
月光博客
C
CXSECURITY Database RSS Feed - CXSecurity.com
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Spread Privacy
Spread Privacy
Know Your Adversary
Know Your Adversary
A
Arctic Wolf
Vercel News
Vercel News
T
Threat Research - Cisco Blogs
T
Threatpost
Apple Machine Learning Research
Apple Machine Learning Research
L
LINUX DO - 热门话题
T
The Exploit Database - CXSecurity.com
N
Netflix TechBlog - Medium
GbyAI
GbyAI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
Tailwind CSS Blog
J
Java Code Geeks
爱范儿
爱范儿
Cisco Talos Blog
Cisco Talos Blog
博客园 - 叶小钗
Latest news
Latest news
C
Check Point Blog
阮一峰的网络日志
阮一峰的网络日志
博客园 - Franky
P
Privacy International News Feed
MyScale Blog
MyScale Blog
Project Zero
Project Zero
Simon Willison's Weblog
Simon Willison's Weblog

夜行人

回家路上 第一期的直播演示项目 震动检测器 正能量 在线参观CodeLab Neverland 发布 CodeLab Adapter 3.3.1 DynamicTable 之 纸糊方向盘 CodeLab DynamicTable: 一个可实施的技术方案 CodeLab Insight 发布 Alpha 版 情人节 Home Assistant 周报 && IoT 周报 (02) Joplin: 关注隐私的 Evernote 开源替代软件 浏览器的未来与 Web 传感器 Home Assistant 周报 && IoT 周报 (01) 百宝箱(01) 论自由 介绍 WebThings Home Assistant 周报 && iot 周报 (00) 百宝箱(00) 毛姆读书心得 传世之作 周末徒步 CodeLab Adapter ❤️ Jupyter/Python 航班 躲雨 夏令营途中 [译]思想--作为一种技术 The future of coding 美国之行 三门问题的程序模拟 从Python转向Pharo https://blog.just4fun.site/post/iot/iot-open-source-projects/ Python异步编程笔记 https://blog.just4fun.site/post/iot/iot-open-source-hardware-community/ 万物积木化开发者社区 CodeLab ❤️ Blender Scratch3技术分析之云变量 API(第7篇) [译]对管道(Pipes)的偏爱 [译]提出正确的问题比得到正确答案更重要 蓝牙设备与Scratch3.0 创建你的第一个Scratch3.0 Extension Scratch3技术分析之项目内部数据(第6篇) Scratch3技术分析之社区 API(第5篇) Scratch3技术分析之User API(第4篇) Scratch3技术分析之项目主页API(第3篇) Scratch3技术分析之静态资源API(第2篇) Scratch3.0、micro:bit与Windows7 https://blog.just4fun.site/post/iot/zerynth-vs-micropython/ 核聚变、方所与半宅空间 可视化编程为何是个糟糕的主意 codelab.club周末聚会 关于codelab.club '下一件大事'是一个房间 Hungry Robot - Eat everything 编程作为一种思考方式 今日简史 史蒂夫·乔布斯传 罗素自选文集 https://blog.just4fun.site/post/edx/tianjin-scratch-ai/ https://blog.just4fun.site/post/edx/richie-cms-openedx/ 徒步武功山 WebUSB与micro:bit 积木化编程与3D场景 夜宿武功山顶 scratch3-adapter接入优必选Alpha系列机器人 https://blog.just4fun.site/post/edx/video-migration-note/ scratch3-adapter重构笔记 https://blog.just4fun.site/post/edx/edx-community-members/ 两种硬件编程风格的比较 使用micro:bit自制PPT翻页笔 柏拉图对话集 scratch3.0 + micro:bit 七月电影放映计划 非营利组织的管理 Screenly--用树莓派让任何屏幕变为可编程的数字标牌 以最佳实践开始你的Django项目 micro:bit与事件驱动 为Scratch3.0设计的插件系统(上篇) OCR应用一例 近两年读过的一些好书 blockly开发之使用python驱动浏览器中的turtle(2) 牛顿新传 文学理论入门 逻辑的引擎 人生的意义 blockly开发之生成并运行js代码(1) blockly开发之hello world(0) micro:bit使用笔记 神器之Termux https://blog.just4fun.site/post/iot/micropython-notes/ Cozmo what is this Scratch的前世今生 下段旅程 我行在远方 爆裂 途中杂记 https://blog.just4fun.site/post/edx/open-edx-startup/ cozmo系列之入门 - 有性格且可编程的机器人 PaperWeekly开发笔记 创业二三事
python笔记之运算符重载
2014-01-09 · via 夜行人

在此对常用的运算符重载做个小结。包括:__init__ , __str__(__repr__) , __call__ , __add__

这部分知识属于面向对象部分。

###关于运算符重载 以下是主要概念:

  • 类可以截获python运算符,可覆盖多数内置类型运算:如 加法,切片, 打印, 点号运算
  • 目的是让对象的用法和外观看起来更像内置类型
  • 运算符重载让对象与python内置对象模型更紧密结合(接口),提供了一致性,以及与预期接口的兼容性
  • 以双下划线命名(X),是特殊钩子,用来拦截运算,定义了固定不变的映射关系
  • 运算符覆盖方法没有默认值,如果没有定义,又执行相应运算,会触发异常

运算符重载的使用者主要是开发工具的人,而不是应用开发这者,不应该盲目使用,清晰优于隐晦

举个例子:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class 	Myclass:
	def __init__(self, value):
		self.data= value
	def __add__(self.other):
		return Myclass(self.date, other)
	def __mul__(self, other):
		self.data = self.data * other

	def display(self):
		print self.data

a = Myclass('abc')	
a.display() 	#'abc'

b = a + 'xyz'
b.display() 	#'abcxyz',注意__add__返回了新对象


a * 3
a.display() 	#'abcabcabc' ,注意__mul__原地修实例

#补充说明:__add__ , __mul__都是`二元运算`。以__add__(self.other)为例,当进行b = a + 'xyz'时,a 赋值给self,'xyz'赋值给other,一般而言实例放在左边,如果实例在右边需要使用__radd__

###更多细节

####init 每次从类产生实例时, python会在自动调用__init__方法(被称为构造器),这是最常用的运算符重载方法.
需要注意的地方是__init__常常用于调用超类的构造器,除非明确调用,否则超类构造器会被覆盖

1
2
3
4
5
6
7
8
class Super:
	def __init__(self,x):
		...default code...

class Sub(Super):
	def __init__(self,x,y):
		Super.__init__(self,x)
		...custom code

####repr__与__str__会返回对象的字符串表现形式 当类的实例打印或转换为字符串时,repr(及其近亲__str)就会自动调用,这些方法可替对象定义更好的显示格式。

1
2
3
4
5
6
7
8
9
class Myclass:
	def __init__(self,value=0):
		self.data = value

	def __repr__(self):
		return 'data is %s' self.data

x =  Myclass()
print x		#data is 0

那么__repr__与__str__的区别是什么,简单地说__repr__更底层,如果没有__str__则调用__repr__(也就是__str__优先),那么可以利用__repr__更底层的特性为所有环境提供统一的字符串显示。为终端用户提供__str__,开发期间则显示__repr__.

####call__拦截调用 当实例被调用时,使用__call,这样可以让实例表现得像函数

1
2
3
4
5
6
7
8
9
class Myclass:
	def __init__(self, value):
		self.value = value
	def __call__(self, other)
		return self.value * other

x = Myclass(2)
x(3)  #6
x(4)  #8

这可能是python中保留状态信息的最好方式,状态的记忆是明确地使用属性赋值运算实现的。 功能很像函数式编程里的闭包

###其他

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#  __del__: 析构方法,与__init__相对
#  __getattr__: 点号运算(获取属性),如:X.name
#  __setattr__: 属性赋值运算, 如: X.name = 'wwj'
#  __getitem__: 索引运算 , X[key],没有__item__时的for循环迭代器。否则__item__优先
#  __setitem__: 索引赋值运算 , 如X[key] = value
#  __iter__: 迭代环境  用于循环,测试,列表,映射
#  __cmp__: 比较 , 如:X == Y , X > Y
#  __lt__: 小于 。 如: X < Y 
#  __eq__: 等于
#  __radd__: 左侧加法,如'abc' + X (对象在右侧)
#  __iadd__: 实地(增强的)加法 ,如:X += Y

文章作者 种瓜

上次更新 2014-01-09