方法运算符重载

2024-04-19 21:47:23 发布

您现在位置:Python中文网/ 问答频道 /正文

Python如何选择使用方法重载的对象?你知道吗

例如:

class a:
    def __init__(self, other):
        self.data = other
    def __add__(self, other):
        return self.data + other
    def __radd__(self,other):
        return self.data + other
X = a(1) 
X+1
1+X

为什么在X + 1表达式中,调用左侧对象中的方法__add__,而在表达式1 + X中,调用右侧对象中的方法__add__?你知道吗


Tags: 对象方法selfadddatareturninit表达式
1条回答
网友
1楼 · 发布于 2024-04-19 21:47:23
X+1

首先,电话:

X.__add__(1)

这是成功的,因此不需要进一步的工作。你知道吗


另一方面,这是:

1+X

电话

(1).__add__(X)

失败的原因是int不知道如何与类a接口。”作为最后的手段,“这是尝试代替:

X.__radd__(1)

docs on ^{}

These functions are only called if the left operand does not support the corresponding operation and the operands are of different types.

相关问题 更多 >