鱼C论坛

 找回密码
 立即注册
查看: 795|回复: 2

[已解决]有关python课后作业43讲的疑问

[复制链接]
发表于 2020-4-10 09:22:36 | 显示全部楼层 |阅读模式

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

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

x
本帖最后由 belf 于 2020-4-10 09:24 编辑

如题,以下是我自己写的代码,我并没有初始化__new__方法。但运行起来也是没有问题的,不知道这样写是否存在问题。另外,想知道初始化__new__方法的目的是什么?希望得到帮助,感谢大家!
  1. class Word(str):
  2.     def __lt__(self,other):
  3.         if self.find(' ') == -1:
  4.             return int.__lt__(len(self),len(other))
  5.         else:
  6.             self = self.split()[0]
  7.             return int.__lt__(len(self),len(other))
  8.         
  9.     def __le__(self,other):
  10.         if self.find(' ') == -1:
  11.             return int.__le__(len(self),len(other))
  12.         else:
  13.             self = self.split()[0]
  14.             return int.__le__(len(self),len(other))

  15.     def __eq__(self,other):
  16.         if self.find(' ') == -1:
  17.             return int.__eq__(len(self),len(other))
  18.         else:
  19.             self = self.split()[0]
  20.             return int.__eq__(len(self),len(other))
  21.         
  22.     def __ne__(self,other):
  23.         if self.find(' ') == -1:
  24.             return int.__ne__(len(self),len(other))
  25.         else:
  26.             self = self.split()[0]
  27.             return int.__ne__(len(self),len(other))

  28.     def __gt__(self,other):
  29.         if self.find(' ') == -1:
  30.             return int.__gt__(len(self),len(other))
  31.         else:
  32.             self = self.split()[0]
  33.             return int.__gt__(len(self),len(other))

  34.     def __ge__(self,other):
  35.         if self.find(' ') == -1:
  36.             return int.__ge__(len(self),len(other))
  37.         else:
  38.             self = self.split()[0]
  39.             return int.__ge__(len(self),len(other))
复制代码

最佳答案
2020-4-10 10:46:45
你这样写也是可以的。
按照小甲鱼的答案,重载__new__方法之后,在创建该类的对象的时候,就把传入的参数字符串进行了处理,删掉了空格以及之后的内容,将之限定成一个单词了。
例如:同样的执行a=Word("work hard"),你的程序得到得到a是字符串"work hard",小甲鱼的答案得到的a是"work"
FireShot Capture 010 - 第043讲:魔法方法:算术运算2 - 课后测试题及答案,《零基础.png

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-4-10 10:46:45 | 显示全部楼层    本楼为最佳答案   
你这样写也是可以的。
按照小甲鱼的答案,重载__new__方法之后,在创建该类的对象的时候,就把传入的参数字符串进行了处理,删掉了空格以及之后的内容,将之限定成一个单词了。
例如:同样的执行a=Word("work hard"),你的程序得到得到a是字符串"work hard",小甲鱼的答案得到的a是"work"
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-4-10 10:59:03 | 显示全部楼层
感谢回答!谢谢!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-8 22:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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