OpenSource GitHub プロジェクトから次のコードを理解しようとしています。__init__
メソッドがなくてもメソッドがあるクラスがあり__new__
ます。コードは次のように与えられます。
class Node(object):
#pylint: disable=W0404
#Singleton-Pattern
_instances = dict()
def __new__(cls, name=None):
""" Instanciates a node from a file, and (name=None) creates a new node
Caution: Filenames are always given relative to the root-dir
When no name is given, a new node is created. """
if(name!=None and cls._instances.has_key(name)):
return(cls._instances[name])
if(name==None): # a new node, lets find a name
for i in itertools.count(0):
name = "node%.4d"%i
if(cls._instances.has_key(name)): continue# new nodes might not been saved, yet
if(path.exists("./nodes/"+name)): continue
break
self = object.__new__(cls)
cls._instances[name] = self
#actuall init-code
from ZIBMolPy.pool import Pool #avoids circular imports
self._pool = Pool() #Pool is a singleton
self._name = name
self._tmp = Store() #for thing that need to be stored temporarly
self._obs = Store()
self.parent = None
if(path.exists(self.dir)):
self.reload()
#self.pool.append(self) #register with pool
return(self)
#---------------------------------------------------------------------------
@property
def obs(self):
return(self._obs)
Python での __new__ と __init__ の使用で__init__
、メソッドと__new__
メソッドの間で1 つの議論を見つけました。最高評価のコメントによると、 、、または
のような不変型をサブクラス化する場合にのみ、 new を使用する必要があります。しかし、ここでは別の理由で使用されていると思います。さらに、クラスに名前を付ける必要がある理由(および一部のフォルダーで何かを行う必要がある理由)と、なぜ呼び出すことができるのかわかりませんstr
int
unicode
tuple
cls
n= Node()
n.obs
関数obsのようにプロパティ関数になりますが、実際にはそうではありません..
私は混乱しています。そうでない場合は、返信を待ちきれません。