
Python运算符重载用法实例分析
本文实例讲述了Python运算符重载用法。分享给大家供大家参考。具体如下:
在Python语言中提供了类似于C++的运算符重在功能:
一下为Python运算符重在调用的方法如下:
Method Overloads Call for
__init__ 构造函数 X=Class()
__del__ 析构函数 对象销毁
__add__ + X+Y,X+=Y
__or__ | X|Y,X|=Y
__repr__ 打印转换 print X,repr(X)
__str__ 打印转换 print X,str(X)
__call__ 调用函数 X()
__getattr_ 限制 X.undefine
__setattr__ 取值 X.any=value
__getitem__ 索引 X[key],
__len__ 长度 len(X)
__cmp__ 比较 X==Y,X<Y
__lt__ 小于 X<Y
__eq__ 等于 X=Y
__radd__ Right-Side + +X
__iadd__ += X+=Y
__iter__ 迭代 For In
1. 减法重载
class Number:
def __init__(self, start):
self.data = start
def __sub__(self, other): #minus method
return Number(self.data - other)
number = Number(20)
y = number – 10 # invoke __sub__ method
class Number:
def __init__(self, start):
self.data = start
def __sub__(self, other): #minus method
return Number(self.data - other)
number = Number(20)
y = number – 10 # invoke __sub__ method
2. 迭代重载
class indexer:
def __getitem__(self, index): #iter override
return index ** 2
X = indexer()
X[2]
for i in range(5):
print X[i]
class indexer:
def __getitem__(self, index): #iter override
return index ** 2
X = indexer()
X[2]
for i in range(5):
print X[i]
3. 索引重载
class stepper:
def __getitem__(self, i):
return self.data[i]
X = stepper()
X.data = 'Spam'
X[1] #call __getitem__
for item in X: #call __getitem__
print item
class stepper:
def __getitem__(self, i):
return self.data[i]
X = stepper()
X.data = 'Spam'
X[1] #call __getitem__
for item in X: #call __getitem__
print item
4. getAttr/setAttr重载
class empty:
def __getattr__(self,attrname):
if attrname == 'age':
return 40
else:
raise AttributeError,attrname
X = empty()
print X.age #call__getattr__
class accesscontrol:
def __setattr__(self, attr, value):
if attr == 'age':
# Self.attrname = value loops!
self.__dict__[attr] = value
else:
print attr
raise AttributeError, attr + 'not allowed'
X = accesscontrol()
X.age = 40 #call __setattr__
X.name = 'wang' #raise exception
class empty:
def __getattr__(self,attrname):
if attrname == 'age':
return 40
else:
raise AttributeError,attrname
X = empty()
print X.age #call__getattr__
class accesscontrol:
def __setattr__(self, attr, value):
if attr == 'age':
# Self.attrname = value loops!
self.__dict__[attr] = value
else:
print attr
raise AttributeError, attr + 'not allowed'
X = accesscontrol()
X.age = 40 #call __setattr__
X.name = 'wang' #raise exception
5. 打印重载
class adder:
def __init__(self, value=0):
self.data = value
def __add__(self, other):
self.data += other
class addrepr(adder):
def __repr__(self):
return 'addrepr(%s)' % self.data
x = addrepr(2) #run __init__
x + 1 #run __add__
print x #run __repr__
class adder:
def __init__(self, value=0):
self.data = value
def __add__(self, other):
self.data += other
class addrepr(adder):
def __repr__(self):
return 'addrepr(%s)' % self.data
x = addrepr(2) #run __init__
x + 1 #run __add__
print x #run __repr__
6. Call调用函数重载
class Prod:
def __init__(self, value):
self.value = value
def __call__(self, other):
return self.value * other
p = Prod(2) #call __init__
print p(1) #call __call__
print p(2)
class Prod:
def __init__(self, value):
self.value = value
def __call__(self, other):
return self.value * other
p = Prod(2) #call __init__
print p(1) #call __call__
print p(2)
7. 析构函数重载
class Life:
def __init__(self, name='name'):
print 'Hello', name
self.name = name
def __del__(self):
print 'Goodby', self.name
brain = Life('Brain') #call __init__
brain = 'loretta' # call __del__
希望本文所述对大家的Python程序设计有所帮助。
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
在神经网络设计中,“隐藏层个数” 是决定模型能力的关键参数 —— 太少会导致 “欠拟合”(模型无法捕捉复杂数据规律,如用单隐 ...
2025-10-21在特征工程流程中,“单变量筛选” 是承上启下的关键步骤 —— 它通过分析单个特征与目标变量的关联强度,剔除无意义、冗余的特 ...
2025-10-21在数据分析全流程中,“数据读取” 常被误解为 “简单的文件打开”—— 双击 Excel、执行基础 SQL 查询即可完成。但对 CDA(Cert ...
2025-10-21在实际业务数据分析中,我们遇到的大多数数据并非理想的正态分布 —— 电商平台的用户消费金额(少数用户单次消费上万元,多数集 ...
2025-10-20在数字化交互中,用户的每一次操作 —— 从电商平台的 “浏览商品→加入购物车→查看评价→放弃下单”,到内容 APP 的 “点击短 ...
2025-10-20在数据分析的全流程中,“数据采集” 是最基础也最关键的环节 —— 如同烹饪前需备好新鲜食材,若采集的数据不完整、不准确或不 ...
2025-10-20在数据成为新时代“石油”的今天,几乎每个职场人都在焦虑: “为什么别人能用数据驱动决策、升职加薪,而我面对Excel表格却无从 ...
2025-10-18数据清洗是 “数据价值挖掘的前置关卡”—— 其核心目标是 “去除噪声、修正错误、规范格式”,但前提是不破坏数据的真实业务含 ...
2025-10-17在数据汇总分析中,透视表凭借灵活的字段重组能力成为核心工具,但原始透视表仅能呈现数值结果,缺乏对数据背景、异常原因或业务 ...
2025-10-17在企业管理中,“凭经验定策略” 的传统模式正逐渐失效 —— 金融机构靠 “研究员主观判断” 选股可能错失收益,电商靠 “运营拍 ...
2025-10-17在数据库日常操作中,INSERT INTO SELECT是实现 “批量数据迁移” 的核心 SQL 语句 —— 它能直接将一个表(或查询结果集)的数 ...
2025-10-16在机器学习建模中,“参数” 是决定模型效果的关键变量 —— 无论是线性回归的系数、随机森林的树深度,还是神经网络的权重,这 ...
2025-10-16在数字化浪潮中,“数据” 已从 “辅助决策的工具” 升级为 “驱动业务的核心资产”—— 电商平台靠用户行为数据优化推荐算法, ...
2025-10-16在大模型从实验室走向生产环境的过程中,“稳定性” 是决定其能否实用的关键 —— 一个在单轮测试中表现优异的模型,若在高并发 ...
2025-10-15在机器学习入门领域,“鸢尾花数据集(Iris Dataset)” 是理解 “特征值” 与 “目标值” 的最佳案例 —— 它结构清晰、维度适 ...
2025-10-15在数据驱动的业务场景中,零散的指标(如 “GMV”“复购率”)就像 “散落的零件”,无法支撑系统性决策;而科学的指标体系,则 ...
2025-10-15在神经网络模型设计中,“隐藏层层数” 是决定模型能力与效率的核心参数之一 —— 层数过少,模型可能 “欠拟合”(无法捕捉数据 ...
2025-10-14在数字化浪潮中,数据分析师已成为企业 “从数据中挖掘价值” 的核心角色 —— 他们既要能从海量数据中提取有效信息,又要能将分 ...
2025-10-14在企业数据驱动的实践中,“指标混乱” 是最常见的痛点:运营部门说 “复购率 15%”,产品部门说 “复购率 8%”,实则是两者对 ...
2025-10-14在手游行业,“次日留存率” 是衡量一款游戏生死的 “第一道关卡”—— 它不仅反映了玩家对游戏的初始接受度,更直接决定了后续 ...
2025-10-13