白鸽天空 发表于 2020-10-8 14:39:49

小甲鱼42课的课后题

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#为什么可以other.total这样的使用前一个函数的计算

疾风怪盗 发表于 2020-10-8 14:52:14

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, b):
      return self.total + b.total# 为什么可以other.total这样的使用前一个函数的计算


a = Nstr(arg='1')
c = Nstr(arg='1')
print(a + c)

是这样用的么?other可以换成其他的形参,就是表示与其相加的另外一个对象,这个对象如果也是这个类的话,也有total这个属性,那就可以这么用吧

如果把c是实例化的 一个没有total属性的类,那就会报错了
class AAAAA:
    pass

a = Nstr(arg='1')
c = AAAAA
print(a + c)
Traceback (most recent call last):
File "D:/python/test/test.py", line 17, in <module>
    print(a + c)
File "D:/python/test/test.py", line 11, in __add__
    return self.total + b.total# 为什么可以other.total这样的使用前一个函数的计算
AttributeError: type object 'AAAAA' has no attribute 'total'
页: [1]
查看完整版本: 小甲鱼42课的课后题