马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 a2854825211 于 2017-7-21 22:41 编辑
今天看了课程,小甲鱼老师有这么个例子:class C(str):
def __new__(a,x):
y = x.upper()
return str.__new__(a,y)
完全不懂这是怎么来的。我照葫芦画瓢写了个代码,然后就报错了。
代码是:class A:
def __init__(self,x):
self.x = str(x)
def printt(self,y):
print (self.x,y)
class B(A):
def __init__(self,x):
self.x = int(x)
>>> b = B(2)
>>> b = B(2.5)
>>> a = A(2.5)
>>> a.printt(3.5)
2.5 3.5
>>> b.printt(3.5)
2 3.5
到这里是正常的 然后我写了第三个类:class C(A):
def __new__(a,x):
x = int(x)
return A.__new__(a,x)
>>> c =C(2.5)
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
c =C(2.5)
File "<pyshell#47>", line 4, in __new__
return A.__new__(a,x)
TypeError: object() takes no parameters
报错了 。 我这么写可能看起来有些搞笑 因为实在是不懂__new__的用法,照葫芦瞎写的 大家帮忙看看,分析下,解释解释__new__的用法,谢谢大家 |