gpt4 book ai didi

python - 如何创建一个不重新创建具有相同输入参数的对象的类

转载 作者:行者123 更新时间:2023-11-28 19:31:55 25 4
gpt4 key购买 nike

我正在尝试创建一个不会重新创建具有相同输入参数的对象的类。当我尝试使用用于创建已存在对象的相同参数实例化一个类时,我只希望我的新类返回一个指向已创建(大量创建)对象的指针。到目前为止,这是我尝试过的:

class myobject0(object):
# At first, I didn't realize that even already-instantiated
# objects had their __init__ called again
instances = {}
def __new__(cls,x):
if x not in cls.instances.keys():
cls.instances[x] = object.__new__(cls,x)
return cls.instances[x]
def __init__(self,x):
print 'doing something expensive'

class myobject1(object):
# I tried to override the existing object's __init__
# but it didnt work.
instances = {}
def __new__(cls,x):
if x not in cls.instances.keys():
cls.instances[x] = object.__new__(cls,x)
else:
cls.instances[x].__init__ = lambda x: None
return cls.instances[x]
def __init__(self,x):
print 'doing something expensive'

class myobject2(object):
# does what I want but is ugly
instances = {}
def __new__(cls,x):
if x not in cls.instances.keys():
cls.instances[x] = object.__new__(cls,x)
cls.instances[x]._is_new = 1
else:
cls.instances[x]._is_new = 0
return cls.instances[x]
def __init__(self,x):
if self._is_new:
print 'doing something expensive'

这是我第一次尝试重写 __new__,我确信我的做法不对。请让我直截了当。

最佳答案

这是一个类装饰器,可以使一个类成为多元素:

def multiton(cls):
instances = {}
def getinstance(id):
if id not in instances:
instances[id] = cls(id)
return instances[id]
return getinstance

(这是 PEP 318 中单例装饰器的一个轻微变体。)

然后,要使您的类成为多类,请使用装饰器:

@multiton
class MyObject( object ):
def __init__( self, arg):
self.id = arg
# other expensive stuff

现在,如果您使用相同的 id 实例化 MyObject,您将获得相同的实例:

a = MyObject(1)
b = MyObject(2)
c = MyObject(2)

a is b # False
b is c # True

关于python - 如何创建一个不重新创建具有相同输入参数的对象的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/669932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com