第42讲作业
本帖最后由 1062195630 于 2021-5-20 18:15 编辑小甲鱼的代码1:
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
小甲鱼的代码2:
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)
我的代码:
class Nstr:
def __new__(cls, arg=''):
if isinstance(arg, str):
total = 0
for each in arg:
total += ord(each)
arg = total
returnarg
a=Nstr('asd')
b=Nstr('zxc')
c=a+b
print(a,b,c)
我的代码会有什么问题吗??
没什么问题,就是甲鱼哥继承了 int 类后改写 __new__
你的是直接返回具体数值对象
哦哦哦。谢谢
页:
[1]