| 
 | 
 
 
发表于 2020-11-19 13:50:54
|
显示全部楼层
 
 
 
 本帖最后由 jackz007 于 2020-11-19 14:17 编辑  
 
 
        看来你完全没有理解类和对象的概念,self 和 other 分别代表两个对象,self . total 是一个对象的属性,other . total 是另一个对象的属性。 
 
        如果 "人" 是一个类的话,每个 "人" 都有一颗心脏,就是说,心脏是 "人" 这个类的一个共有(或必有)属性,你、我都是人类的一员(实例),其实就是 "人" 这个类的一个对象,所以,你、我也都有一颗心脏,可是,你的心脏肯定不是我的心脏,那么,如果 self . total 是我的心脏的话,那么, other . total 就是你的心脏了。 
 
        试试下面的代码可以加深理解 
- #coding:gbk
 
 - class Nstr:
 
 -     def __init__(self, arg='  '):
 
 -         if isinstance(arg, str):
 
 -             self.total = 0
 
 -             for each in arg:
 
 -                 self.total += ord(each)
 
 -         else:
 
 -             print("参数错误!")
 
  
-     def __add__(self, other):
 
 -         return self.total + other.total
 
  
-     def __sub__(self, other):
 
 -         return self.total - other.total
 
  
-     def __mul__(self, other):
 
 -         return self.total * other.total
 
  
-     def __truediv__(self, other):
 
 -         return self.total / other.total
 
  
-     def __floordiv__(self, other):
 
 -         return self.total // other.total
 
  
- a = Nstr('abc')                  # 用到 __init__(self, arg='  ')
 
 - b = Nstr('ABC')                  # 用到 __init__(self, arg='  ')
 
 - print('a + b =' , a + b)         # a . total +  b . total , 用到 __add__(self, other)
 
 - print('a - b =' , a - b)         # a . total -  b . total , 用到 __sub__(self, other) 
 
 - print('a * b =' , a * b)         # a . total *  b . total , 用到 __mul__(self, other) 
 
 - print('a / b =' , a / b)         # a . total /  b . total , 用到 __truediv__(self, other)
 
 - print('a // b =' , a // b)       # a . total // b . total , 用到 __floordiv__(self, other) 
 
  复制代码 
        代码中的对象 a 对应魔法方法中的 self,对象 b 对应 other 。  |   
 
 
 
 |