python - 我可以更改 Python 中的默认 __add__ 方法吗?
问题描述
是否可以更改默认__add__
方法以执行其他操作而不只是添加?
例如,如果目标是这一行:
5+5
getThe answer is 10
或其他类似的东西,0
通过更改__add__
为 bex-y
而不是x+y
?
我知道我可以改变__add__
自己的课程:
class Vec():
def __init__(self,x,y):
self.x = x
self.y = y
def __repr__(self):
return f'{self.x, self.y}'
def __add__(self, other):
self.x += other.x
self.y += other.y
return Vec(self.x,self.y)
v1 = Vec(1,2)
v2 = Vec(5,3)
v1+v2
# (6, 5)
我可以以某种方式定位默认__add__
方法来改变其行为吗?我直观地认为__add__
在每个默认数据类型中定义了返回特定结果,但话说回来,该__add__
方法是我们为特定类更改它时要解决的问题,那么,是否可以更改主要__add__
逻辑?
这些方面的东西?
class __add__():
...
解决方案
是的,您可以重载用户定义的类中的任何内容。
class Vec():
def __init__(self,x,y):
self.x = x
self.y = y
def __repr__(self):
return f'{self.x, self.y}'
def __add__(self, other):
self.x += other.x
self.y += other.y
return Vec(self.x,self.y)
v1 = Vec(1,2)
v2 = Vec(5,3)
print(v1+v2)
# using lambda function
Vec.__add__ = lambda self,other: Vec(self.x-other.x,self.y-other.y)
print(v1+v2)
# using "normal" function
def add(self,other):
self.x -= other.x
self.y -= other.y
return Vec(self.x,self.y)
Vec.__add__ = add
print(v1+v2)
不适用于内置类型,例如导致TypeError: can't set attributes of built-in/extension type 'set'
另请注意,您的实现__add__
修改了我不喜欢的原始实例..(只是我的注释)
推荐阅读
- kubernetes - 不同 Kubernetes 集群中的 Hazelcast 节点之间的数据是否强一致?
- javascript - 在范围输入中,当最小值和最大值相等时,幻灯片应该只是一个点?
- python - 在 GCP 中使用 Cloud Functions 抓取页面并将其加载到 BigQuery
- compilation - 尝试使用 ncurses 运行 C 代码时出现编译和链接错误
- jmeter - JMeter摘要报告中两个字段的含义 - 测试和总计
- sql - 如何知道 WHERE 语句中有多少条件满足其条件?
- xml - 在 Jackson XML 中处理 xml 扩展
- ruby-on-rails-5 - 将演示/示例代码附加到 API 文档
- xamarin - 当列表项是包裹在 ContentView 中的 SwipeView 时,ListView 的 ItemSelected 事件不会触发
- node.js - 从 webapp 登录到 chrome 扩展,就像语法一样