|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
原题:
定义一个类 Nstr,当该类的实例对象间发生的加、减、乘、除运算时,将该对象的所有字符串的 ASCII 码之和进行计算。
正确答案一:
- 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
复制代码
正确答案二:
- class Nstr(int):
- def __new__(cls, arg=0):
- if isinstance(arg, str):
- total = 0
- for each in arg:
- total += ord(each)
- arg = total
- return int.__new__(cls, arg)
复制代码
问题:
1. 第二个答案中,为何没有定义加、减、乘、除,却都能够顺利计算出来呢?
2. 第二个答案,为何能做到如此简练?
本帖最后由 jackz007 于 2021-3-9 14:09 编辑
答案一是 ”白手起家“,所有用到的方法都需要进行定义,缺一不可;答案二继承自 int 类,可以直接使用父类的所有方法,在完成对象定义之后,Nstr 的对象与一个普通的整型数没有任何差异。
|
|