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