【发布时间】:2012-05-11 13:38:39
【问题描述】:
我会尽量简化这里的情况,当覆盖__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))
【问题讨论】:
-
你想做什么?此外,对内置类进行子类化通常比人们想象的更棘手,也更没用。 :-)
-
不想用大量代码打扰你们,我试图将问题简化为(我的真实代码有一些比 A 和 B 更复杂的类),而且我倾向于从基类派生在可能的情况下,因为我不必投射和包装......但我仍在学习。有多个超类应该创建对象时的疑问?不应该是“对象”,后者由 init 装饰(可能会丢失其他超级“new”完成的一些特定操作),还是有办法调用几个“new”的所有超级不跳过代码?
-
你没有回答这个问题:你想做什么?您的代码的目的是什么?
-
我们询问您的目的的原因是几乎可以肯定有一种更简单的方法可以做到这一点。在 Python 中很少需要多重继承、弱引用或覆盖
__new__。 -
它是一个支持多种类型对象的范围,在我开始弄乱多态对象之前它一直很好。上面的例子只是尝试隔离案例,了解python的对象组成和谁调用谁
标签: python python-3.x