|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
定义一个类继承于str类,把传入的字符串变为大写?。求教为什么会报错
- def DaXie(str):
- def __init__(self,string):
- self.string = string.upper()
- def printX(self):
- return self.string
- a = DaXie('Hello world')
- a.printX()
复制代码
报错代码:Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
a.printX()
AttributeError: 'NoneType' object has no attribute 'printX'
本帖最后由 Twilight6 于 2020-7-4 18:38 编辑
哈哈 楼上都是正解
这边也提一点:继承不可变类型,应该用的是 __new__ 魔法方法比较合理
- class DaXie(str):
- def __new__(self, string):
- self.string = string.upper()
- return self.string
- a = DaXie('Hello world')
- print(a)
复制代码
|
|