Python基礎課:實現一個正方形類的加減乘除


 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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM