Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีโอเวอร์โหลดออเปอเรเตอร์ Python กับหลาย operand

คุณสามารถโอเวอร์โหลดออเปอเรเตอร์ Python กับหลาย operand ได้เหมือนกับที่คุณทำกับ binary operators ตัวอย่างเช่น หากคุณต้องการโอเวอร์โหลดออเปอเรเตอร์ + สำหรับคลาส คุณจะทำดังนี้:

ตัวอย่าง

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