1 class Square: 2 def __init__(self, wh): #因為是正方形, 只取一條邊的長度 3 if isinstance(wh,(int,float)): 4 self.wh = wh 5 else: 6 raise TypeError 7 8 def __add__(self, other): 9 self_area = self.wh * self.wh #計算self面積 10 other_area = other.wh * other.wh #計算other面積 11 return self_area + other_area #相加 x+y 12 13 def __sub__(self,other): 14 self_area = self.wh * self.wh #計算self面積 15 other_area = other.wh * other.wh #計算other面積 16 return self_area - other_area #相減 x-y 17 18 def __mul__(self,other): 19 self_area = self.wh * self.wh #計算self面積 20 other_area = other.wh * other.wh #計算other面積 21 return self_area * other_area #相乘 x*y 22 23 def __mod__(self,other): 24 self_area = self.wh * self.wh #計算self面積 25 other_area = other.wh * other.wh #計算other面積 26 return self_area % other_area #相除 x%y 27 28 s1 = Square(3) 29 s2 = Square(4)