Python 類,函式過載

houyanhua1發表於2017-09-30
class complex:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def show(self):
        print(self.x, "+", self.y, "i")

    def __add__(self, other):        #過載,對原來的函式作了新的定義和解釋
        if type(other)==type(self):  #過載complex+complex,判斷型別
            return complex(self.x + other.x, self.y + other.y)  # 加法的返回值
        elif type(other)==type(10):  #過載complex+int,判斷型別
            return complex(self.x + other, self.y + other)


c1 = complex(1, 2)
c2 = complex(3, 5)
c1.show()
c2.show()
# c3=c1+c2
# c3=c1.__add__(c2)
c3 = c1 + 10  #complex+int
c3.show()
c4 = c3 + c2  #complex+complex
c4.show()


相關文章