鱼C论坛

 找回密码
 立即注册
查看: 1163|回复: 1

[已解决]小甲鱼42课的课后题

[复制链接]
发表于 2020-10-8 14:39:49 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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
  1. class Nstr:
  2.     def __init__(self, arg=''):
  3.         if isinstance(arg, str):
  4.             self.total = 0
  5.             for each in arg:
  6.                 self.total += ord(each)
  7.         else:
  8.             print('您输入的参数错误!')

  9.     def __add__(self, b):
  10.         return self.total + b.total  # 为什么可以other.total这样的使用前一个函数的计算


  11. a = Nstr(arg='1')
  12. c = Nstr(arg='1')
  13. print(a + c)
复制代码


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

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

  3. a = Nstr(arg='1')
  4. c = AAAAA
  5. 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'
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-10-8 14:52:14 | 显示全部楼层    本楼为最佳答案   
  1. class Nstr:
  2.     def __init__(self, arg=''):
  3.         if isinstance(arg, str):
  4.             self.total = 0
  5.             for each in arg:
  6.                 self.total += ord(each)
  7.         else:
  8.             print('您输入的参数错误!')

  9.     def __add__(self, b):
  10.         return self.total + b.total  # 为什么可以other.total这样的使用前一个函数的计算


  11. a = Nstr(arg='1')
  12. c = Nstr(arg='1')
  13. print(a + c)
复制代码


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

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

  3. a = Nstr(arg='1')
  4. c = AAAAA
  5. 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'
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-9 01:44

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表