我正在尝试为我的一组不可变的类创建一个记忆系统,用于处理符号表达式。到目前为止,我得到的信息如下所示。我不喜欢的事实是,我不能直接阻止对__init__
的调用,而必须在对象( new_inst
属性)中填充一些东西来跟踪__init__
方法是否应该做任何事情。有没有更好的方法来做这件事?
( new_inst
参数只是我告诉__new__
是否“停止”对__init__
的调用的一种简单方法。实际上,这将基于对象是否已经存在于对象缓存中,并且不是__new__
或__init__
的参数)。
my_cache = {}
class Base(object):
def __new__(cls, *args, **kwargs):
signature = (cls, args)
if signature in my_cache:
self = my_cache[signature]
self.new_inst = True
else:
self = object.__new__(cls, *args, **kwargs)
my_cache[signature] = self
self.new_inst = False
return self
class A(Base):
def __init__(self, a):
if not self.new_inst:
print "Initializing A object with a=%d"%(a,)
self.a = a
class B(Base):
def __init__(self, a, b):
if not self.new_inst:
print "Initializing B object with a=%d, b=%d"%(a,b)
self.a = a
self.b = b
a1 = A(1)
a2 = A(1)
a3 = A(3)
b1 = B(1, 2)
b2 = B(1, 2)
b3 = B(1, 3)
print id(a1), id(a2), id(a3)
print id(b1), id(b2), id(b3)
输出:
Initializing A object with a=1
Initializing A object with a=3
Initializing B object with a=1, b=2
Initializing B object with a=1, b=3
140246850102904 140246850102904 140246850102960
140246850103016 140246850103016 140246850103072
编辑:显然我并不清楚我的意思,所以这里有一个更具体的例子。如您所见,第二个A(1)不会导致第二次初始化,并且它返回相同的id。
发布于 2015-09-19 03:14:20
这是一个更短的版本的基础。新的
def __new__(cls, *args, **kwargs):
signature = (cls, args)
new_inst = signature in my_cache
self = my_cache.get(signature, object.__new__(cls, *args, **kwargs))
self.new_inst = new_inst
return self
这不会节省太多的处理时间,但它更干净,更有Pythonic风格。我还没有看到一种更简洁的方法来检测新实例并在分配后设置它。
https://stackoverflow.com/questions/32641447
复制相似问题