python在__new__函数中用pickle做cache, 结果导致无限递归?
如题所述, 下述代码会导致无限递归。 这是对odoo中registry的简化, new 方法里面的东西是已经有的, 请问各位如何解决
import pickleclass Cache:
def __init__(self):
self.d = {}
def __setitem__(self, obj, val):
self.d[obj] = pickle.dumps(val)
def __getitem__(self, obj):
return pickle.loads(self.d[obj])
class Car:
cache = Cache()
def __reduce__(self):
return self.__class__, (self.name,)
def __new__(cls, name):
try:
return cls.cache[name]
except KeyError:
return cls.new(name)
@classmethod
def new(cls, name):
car = object.__new__(cls)
car.init(name)
cls.cache[name] = car
return car
def init(self, name):
self.name = name
def __repr__(self):
return self.name
a = Car('audi')
b = Car('audi')
回答:
object.__new__
會觸發 Car
的 __new__
。所以應該將 new
改爲:
python">@classmethoddef new(cls, name):
cls.init(cls, name)
cls.cache[name] = cls
return cls
以上是 python在__new__函数中用pickle做cache, 结果导致无限递归? 的全部内容, 来源链接: utcz.com/p/938069.html