|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- '''
- 2. 定义一个类 Nstr,当该类的实例对象间发生的加、减、乘、除运算时,
- 将该对象的所有字符串的 ASCII 码之和进行计算:
- >>> a = Nstr('FishC')
- >>> b = Nstr('love')
- >>> a + b
- 899
- >>> a - b
- 23
- >>> a * b
- 201918
- >>> a / b
- 1.052511415525114
- >>> a // b
- 1
- '''
- class Nstr(int):
- def __new__(cls, arg):
- total = 0
- for i in arg:
- total += ord(i)
- return total # 这个total
- 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('FishC')
- b = Nstr('love')
- print(a+b)
- print(a*b)
- print(a/b)
- print(a//b)
复制代码
返回的这个total是类属性么?
本帖最后由 isdkz 于 2022-4-22 23:25 编辑
实际上,你这里的 Nstr 根本就没有 total 属性,所以调用 __add__、__sub__、__mul__、
__truediv__、__floordiv__ 都是会出错的,但是你的代码为什么没有报错呢,因为 total 是一个 int,
所以 __new__ 实际上是返回了一个 int 对象,并不是 Nstr 对象,你可以 print(type(a)) 看看 a 的类型,
所以你这里 a + b ,a * b,a / b ,a // b 调用的是 int 对象的方法,跟你在 Nstr 类中重写的方法没有半毛钱关系
|
|