2

同じ入力パラメーターでオブジェクトを再作成しないクラスを作成しようとしています。既存のオブジェクトの作成に使用されたのと同じパラメーターでクラスをインスタンス化しようとすると、新しいクラスが既に作成された (高価に作成された) オブジェクトへのポインターを返すようにするだけです。これは私がこれまでに試したことです:

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__あり、私はそれを正しい方法で行っていないと確信しています。私を正してください。

4

3 に答える 3

15

クラスをマルチトンにするクラスデコレータは次のとおりです。

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
于 2011-09-21T01:27:16.197 に答える
7

まず、Python で大文字のクラス名を使用します。

次に、ファクトリデザイン パターンを使用してこの問題を解決します。

class MyObject( object ):
    def __init__( self, args ):
        pass # Something Expensive

class MyObjectFactory( object ):
    def __init__( self ):
        self.pool = {}
    def makeMyObject( self, args ):
        if args not in self.pool:
            self.pool[args] = MyObject( args )
        return self.pool[args]

これは、新しいクラス レベルのオブジェクト プールを使用するよりもはるかに簡単です。

于 2009-03-21T20:31:15.173 に答える