鱼C论坛

 找回密码
 立即注册
查看: 1394|回复: 6

小甲鱼第43课的课后作业

[复制链接]
发表于 2020-2-13 17:31:41 | 显示全部楼层 |阅读模式

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

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

x
答案代码如下:
class Word(str):
    def__new__(cls,word):
        if ' 'in word:
            print'Value contains spaces.Truncating to the first spacd.'
            word=word[:word.index(' ')]
            return str.__new__(cls,word)
这里对 return str.__new__(cls,word)不是很理解,
为什么返回值给到了基类的__new__(cls,word)呢
基类的__new__本来应该是默认的objest的函数吧

我知道__new__是创建一个实例对象用到的函数
求大佬能说下,这里的返回给基类是什么道理呢

感谢感谢
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-2-13 17:34:20 | 显示全部楼层
  1. return str.__new__(cls,word)
复制代码


这里是让父类的 __new__ 去处理 word。如果直接 return word,类型是不一样的。

  1. >>> class Word(str):
  2.         def __new__(cls, word):
  3.                 return str.__new__(cls, word)

  4.        
  5. >>> type(Word('Python'))
  6. <class '__main__.Word'>
  7. >>> class Word(str):
  8.         def __new__(cls, word):
  9.                 return word

  10.        
  11. >>> type(Word('Python'))
  12. <class 'str'>
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-2-13 18:57:12 | 显示全部楼层
zltzlt 发表于 2020-2-13 17:34
这里是让父类的 __new__ 去处理 word。如果直接 return word,类型是不一样的。

我的理解是处理好后的对象再传递给这个子类的init?
怎么回到这个子类呢。。。不是交给父类的new去创建了吗
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-2-13 19:00:03 | 显示全部楼层
stone_qaq 发表于 2020-2-13 18:57
我的理解是处理好后的对象再传递给这个子类的init?
怎么回到这个子类呢。。。不是交给父类的new去创建了 ...

它会自动执行子类的 __init__() 。

  1. >>> class A(str):
  2.         def __init__(self, word):
  3.                 print("__init__()")
  4.                 super().__init__()
  5.         def __new__(cls, word):
  6.                 return str.__new__(cls, word)

  7.        
  8. >>> a = A('a')
  9. __init__()
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-2-13 19:57:12 | 显示全部楼层
zltzlt 发表于 2020-2-13 19:00
它会自动执行子类的 __init__() 。

class A(str):
        def __new__(cls, word):
                return str.__new__(cls, word)
        def __init__(self, word):
                print("__init__()")
                super().__init__()
               
SyntaxError: inconsistent use of tabs and spaces in indentation
为啥会报缩进的错呢。。。我也检查了没问题呀
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-2-18 22:12:20 | 显示全部楼层
把缩进前面的空格删掉就好了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-8-6 17:49:45 | 显示全部楼层
zltzlt 发表于 2020-2-13 17:34
这里是让父类的 __new__ 去处理 word。如果直接 return word,类型是不一样的。

噢,原来new处理过后类型不一样!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-11 16:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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