在类外使用Python重载运算符

z18hc3ub  于 2023-03-31  发布在  Python
关注(0)|答案(2)|浏览(108)
class A:
    def __init__(self,m1,m2):
        self.m1 = m1
        self.m2 = m2

    def __add__(self, other):
        ''' add takes 2 objects basically objects on RHS and LHS of + say a + b '''
        print("Inside add")
        s3 = A(self.m1+other.m1,self.m2+other.m2)
        return s3

    def disp(self):
        print('{} {}'.format(self.m1,self.m2))

    def __str__(self):
        return '{} {}'.format(self.m1,self.m2)

def __add__(self,other):
    return self*other

a = 2+5
print(a)

所见输出为:7而expected是10,因为我试图用乘法操作覆盖隐式的add函数。这里发生了什么?运算符重载只适用于pytclass吗?

wpx232ag

wpx232ag1#

class A:
   def __init__(self,m):
       self.m=m
   def __str__(self):
      return str(self.m)
   #multiply two objects
   def __mul__(self,other):
      t=self.m*other.m
      return A(t)
   #add two objects
   def __add__(self,other):
       t=self.m+other.m
      return A(t)
obj1=A(2)
obj2=A(5)
#calling operator overloading of '*'
print(obj1*obj2)
#calling operator overloading of '+'
print(obj1+obj2)
4xrmg8kj

4xrmg8kj2#

您可以在类外部定义一个函数,并将魔术运算符重载属性定义/重定义为该函数

class A:
    def __init__(self,m1,m2):
        # your code here
        .
        .
        .

    def __add__(self, other):
        .
        .
        .

# code outside class
def f(self, other):  # don't need to use 'self'. can have any name
    return self * other

A.__add__ = f  # redefine addition

a = 2+5
print(a)

请注意,这对内置类型不起作用。

相关问题