Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Python looks for special methods like <code>__getattr__</code> in an instance's bases <code>__dict__</code>s, not in the instance's <code>__dict__</code>.</p> <p><code>self.tool</code> is a class. <code>self.tool.test</code>, therefore, will call the <code>__getattr__</code> of <code>self.tool</code>'s class (which is <code>object</code>) -- this is not what we want to happen.</p> <p>Instead, make <code>self.tool</code> an instance, whose class has a <code>__getattr__</code>:</p> <pre><code>class Foo(object): def __init__(self): self.NameList=[] # add new class to ourself toolcls = type('tool', (object,), { '__getattr__' : self.__getattr__, } ) self.tool = toolcls() self.NameList.append( "test" ) # should be called by our newly added "tool" object but is only called sometimes... def __getattr__(self, attr): # print("__getattr__: (%s, %s)" % (self.__class__.__name__, attr) ) if( attr in self.NameList ): return( 99 ) raise AttributeError("--%r object has no attribute %r" % ( type(self).__name__, attr)) foo = Foo() print( "foo.tool.__getattr__=%d" % foo.tool.__getattr__("test") ) print( "foo.tool.test=%d" % foo.tool.test ) </code></pre> <p>yields</p> <pre><code>foo.tool.__getattr__=99 foo.tool.test=99 </code></pre> <p>Also, beware that the above code can lead to infinite recursion if an instance of <code>Foo</code> is made without <code>self.NameList</code> being defined. See <a href="http://nedbatchelder.com/blog/201010/surprising_getattr_recursion.html">Ned Batchelder's post on this suprising pitfall</a>.</p> <p>To protect against the possibility of infinite recursion here, use</p> <pre><code>def __getattr__(self, attr): # print("__getattr__: (%s, %s)" % (self.__class__.__name__, attr) ) if attr == 'NameList': raise AttributeError() if( attr in self.NameList ): return( 99 ) raise AttributeError("--%r object has no attribute %r" % ( type(self).__name__, attr)) </code></pre>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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