Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

여러 피연산자로 Python 연산자 오버로딩을 수행하려면 어떻게 해야 합니까?


이진 연산자에 대해 수행하는 것처럼 여러 피연산자로 Python 연산자 오버로딩을 수행할 수 있습니다. 예를 들어, 클래스에 대한 + 연산자를 오버로드하려면 다음을 수행합니다. -

예시

class Complex(object):
   def __init__(self, real, imag):
      self.real = real
      self.imag = imag
   def __add__(self, other):
      real = self.real + other.real
      imag = self.imag + other.imag
      return Complex(real, imag)
   def display(self):
      print(str(self.real) + " + " + str(self.imag) + "i")

      a = Complex(10, 5)
      b = Complex(5, 10)
      c = Complex(2, 2)
      d = a + b + c
      d.display()

출력

이것은 출력을 제공합니다 -

17 + 17i