鱼C论坛

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

关于继承str类修改__init__的问题

[复制链接]
发表于 2017-2-18 21:39:27 | 显示全部楼层 |阅读模式

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

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

x
        请大神解惑,43章课后作业定义一个类,根据对象的长度进行比较。课后答案说必须用__new__,因为str类不可变,但是为什么我做的这个也可以达到目标,请解惑。

class Nstr(str):
    def __init__(self, arg=''):
        if isinstance(arg, str):
            self.length = len(arg)
        else:
            print("参数错误!")
    def __lt__(self, other):
        return self.length < other.length
    def __gt__(self, other):
        return self.length > other.length
a = Nstr('zzz')
b = Nstr('acbc')
print(a < b)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-2-20 11:10:21 | 显示全部楼层
还没学到那里来,帮顶
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-2-25 17:13:32 | 显示全部楼层
本帖最后由 yamal 于 2017-2-25 17:29 编辑

class Nstr(str):


    def __xor__(self,other):
        if ' ' in self:
            self=self.split(' ',1)
            self=self[0]
        if ' ' in other:
            other=other.split(' ',1)
            other=other[0]
        if len(self)>len(other):
            print('%s更长'% self)
        elif len(self)<len(other):
            print('%s更长'% other)
        else:
            print('一样长')

aa=Nstr('yamal is good girl')
bb=Nstr('fishc is a hehe ')
我这么写得,也可以执行
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-11 21:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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