我将尝试在这里简化这种情况,当__new__
如下覆盖时,我不知道调用 super__new__
来完成这项工作的正确方法,我做得好吗还是有其他方法可以做到这一点?
super().__new__(cls)
没有像我预期的那样产生正确的结果
我是python初学者,请耐心等待,我C++流利
import weakref
class A(str):
def __init__(self,s):self.a=s
class B(str):
def __init__(self,s):self.b=s
class P(A,B):
manifest=weakref.WeakValueDictionary()
def __new__(cls,a,b):
o=P.manifest.get(a+b)
if not o:
print(a,b,super(P,cls))
#i thought this first should be used because __init__ puts the values in
#and we index the manifest with parameters [a+b]
#o=super().__new__(cls)#produces unique results for all requests?!?
#so i called like this and it works (either with a or b)
o=super().__new__(cls,a)#why favoring a over b?
#o=super().__new__(cls,b)#why favoring b over a?
#o=super().__new__(cls,a,b)#its an error (of coz)
P.manifest[a+b]=o
print("using",id(o))
return o
def __init__(self,a,b):
A.__init__(self,a)
B.__init__(self,b)
p=P("a","b")
q=P("a","b")
r=P("a","x")
print(id(p),id(q),id(r))