Note that there are some explanatory texts on larger screens.

plurals
  1. POSomething with __new__ and property
    primarykey
    data
    text
    <p>I try to understand the following code from some OpenSource GitHub project. There is a class without <code>__init__</code> but with a <code>__new__</code> method. The code is given as:</p> <pre><code>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) </code></pre> <p>I found one discussion beween the <code>__init__</code> method and the <code>__new__</code> method at <a href="https://stackoverflow.com/questions/674304/pythons-use-of-new-and-init">Python&#39;s use of __new__ and __init__?</a> According to the highest rated comment, one should only use new if one is subclassing an immutable type like <code>str</code>, <code>int</code>, <code>unicode</code> or <code>tuple</code>. But I think here it is used for some other reason. Further more I don't understand why the class <code>cls</code> should have a name (and why it should have anything todo with some folders) and why I can call </p> <pre><code>n= Node() n.obs </code></pre> <p>like the function obs would be a property function, but it is actually not..</p> <p>I am confused. If your not, I cant wait for your respond.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload