zoukankan      html  css  js  c++  java
  • 对象的加减乘除运算demo

     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)
    

      

    注意:return的东西也可以是类的实例化,返回一个对象。

  • 相关阅读:
    css3 box-shadow
    JS的Document属性和方法
    简单配色方案web
    ps中参考线的使用技巧
    min-width() ie6
    js 模拟右键菜单
    display:table-cell
    js opener 的使用
    js的 new image()
    CSS 中文字体 Unicode 编码方案
  • 原文地址:https://www.cnblogs.com/wangbaihan/p/8150898.html
Copyright © 2011-2022 走看看