社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python运算符重载顺序[重复]

MYousefi • 3 年前 • 232 次点击  

一个简单的例子——我想用一个point类来描述二维空间中的一个点。我想把两点加在一起。。。以及将两个点相乘(不要问我为什么),或将一个点乘以一个标量。现在,我将只把它当作标量是整数来实现,但分数或浮点数也很容易实现。

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return "({0},{1})".format(self.x, self.y)

    def __add__(self, other):
        x = self.x + other.x
        y = self.y + other.y
        return Point(x, y)

    def __mul__(self, other):
        if isinstance(other, Point):
            x = self.x * other.x
            y = self.y * other.y
            return Point(x, y)
        elif isinstance(other, int):
            x = self.x * other
            y = self.y * other
            return Point(x, y)

>>> p1 = Point(2, 3)
>>> p2 = Point(-1, 2)
>>> print(p1*p2)
(-2,6)
>>>print(p1*4)
(8,12)

但当我反转标量和点对象的顺序时,它不起作用:

>>>print(4*p1)
Traceback (most recent call last):   
  File "<input>", line 1, in <module> TypeError: unsupported operand type(s) for *:
'int' and 'Point'

如果我写的是'4*p1'或'p1*4',我仍然会执行相同的代码并返回相同的答案,那么我如何编写代码呢?我是否通过重载 骡子 整数对象的运算符还是有其他方法?

注意:我的简短示例的代码是从 https://www.programiz.com/python-programming/operator-overloading

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131405
文章 [ 1 ]  |  最新文章 3 年前
boymeetscode
Reply   •   1 楼
boymeetscode    7 年前

(当我准备提交问题时,我正在标记,并找到了答案。我认为值得在这里记录它,以便其他人可以轻松找到。)

定义 __rmul__(self, other) .这代表正确的乘法运算。当左边的对象无法相乘时(在上面的例子中,整数不知道如何与右边的Point类相乘),Python将查看右边的对象,看看 __rmul_______________ 定义了特殊的方法,它有效吗?如果是这样,它将使用这个实现。

对于可交换的类(即,可以将 B还是B A)并得到相同的结果)您可以将其定义为:

def __mul__(self, other):
    if isinstance(other, Point):
        x = self.x * other.x
        y = self.y * other.y
        return Point(x, y)
    elif isinstance(other, int):
        x = self.x * other
        y = self.y * other
        return Point(x, y)

def __rmul__(self, other):
    return self.__mul__(other)