Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to dynamically override __setitem__? (no subclass)
    primarykey
    data
    text
    <p>I'm not able to override some builtin functions, such as '__setitem__', in <strong>Python2.7</strong> (although the same occurs in previous versions I tested)</p> <p>Although I know this is easy to do via subclassing, this is not what I want here, I need to be able to dynamically override these methods.</p> <p>Apparently, when my class is a subclass of '<strong>object</strong>', the overridden method always ends up calling the original one, but when my class is not an '<strong>object</strong>', it works:</p> <pre><code>&gt;&gt;&gt; def new_implementation(k, v): ... print 'New implementation' ... ### class that extends object &gt;&gt;&gt; class ExtendsObject(object): ... def __setitem__(self, k, v): ... print 'ExtendsObject implementation' ... ### Checking implementation &gt;&gt;&gt; obj = ExtendsObject() &gt;&gt;&gt; obj[0]=0 ExtendsObject implementation ### trying to override setitem, no success &gt;&gt;&gt; obj.__setitem__ = new_implementation &gt;&gt;&gt; obj[0]=0 ExtendsObject implementation ### class that does NOT extends object &gt;&gt;&gt; class DoesNotExtend: ... def __setitem__(self, k, v): ... print 'DoesNotExtend implementation' ... ### Checking implementation &gt;&gt;&gt; obj_2 = DoesNotExtend() &gt;&gt;&gt; obj_2[0]=0 DoesNotExtend implementation ### overriding now works! &gt;&gt;&gt; obj_2.__setitem__ = new_implementation &gt;&gt;&gt; obj_2[0]=0 New implementation </code></pre> <p>For some reason, it seems that objects use some different method resolution order for these built-in functions.</p> <p>Is this a bug? Am I doing something wrong?</p>
    singulars
    1. This table or related slice is empty.
    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