I try to understand the following code from some OpenSource GitHub project. There is a class without __init__
but with a __new__
method. The code is given as:
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)
I found one discussion beween the __init__
method and the __new__
method at Python's use of __new__ and __init__?
According to the highest rated comment, one should only use new if one is subclassing an immutable type like str
, int
, unicode
or tuple
. But I think here it is used for some other reason. Further more I don't understand why the class cls
should have a name (and why it should have anything todo with some folders) and why I can call
n= Node()
n.obs
like the function obs would be a property function, but it is actually not..
I am confused. If your not, I cant wait for your respond.