请教 关于python魔法方法问题
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
def __add__(self, other):
return self.total + other.total这句返回值是什么意思求教一下self.total + other.total self是第一个参数。在python里是指“实例”本身。就是自己。这个class Nstr有一个属性是total
other是第二个参数,它代表另一个class Nstr的实例。当然它也有一个属性total
__add__是一个重载加号的函数。意思是将两个class Nstr实例相加,结果等于两个实例的x变量相加之和。 实例化对象加同类的实例化对象时,返回自己的total和相加对象的total之和 塔利班 发表于 2018-5-13 15:34
实例化对象加同类的实例化对象时,返回自己的total和相加对象的total之和
other.total
请问呢这个呢没懂 铁岭小刚fishc 发表于 2018-5-13 15:53
other.total
请问呢这个呢没懂
实例对象都有total属性,只不过是加号后边的实例的total属性 顶一下 还不会
小阳光 发表于 2018-5-14 13:16
还不会
。。。。 例如
a=Nstr('I love')
b=Nstr('FishC')
a+b调用__add__(a,b): return a.total+b.total
两个同类的实例对象相加,分别调用各自的total相加并返回
页:
[1]