Inheritance from builtin list and override of methods.

Carl Banks pavlovevidence at gmail.com
Mon Nov 27 10:21:17 EST 2006


Fredrik Lundh wrote:
> Michalis Giannakidis wrote:
>
> > Could someone please explain the reasoning/behabiour of these?
>
> in general, methods on C objects are implemented in terms of operations
> on the internal data structures, not in terms of a subset of the methods
> already provided by the object.

True, and it's also true for many Python classes.  Here's a very silly
example:

class Cons(object):
    def __init__(self,car,cdr):
        self.car = car
        self.cdr = cdr
    def __getitem__(self,key):
        if key == "car":
            return self.car
        if key == "cdr":
            return self.cdr
        raise KeyError(key)
    def __getitem__(self,key,value):
        if key == "car":
            self.car = value
        if key == "cdr":
            self.cdr = value
        raise KeyError(key)
    def swap(self):
        self.car,self.cdr = self.cdr,self.car

So hooking into __getitem__ and __setitem__ won't let you inpect the
swap operation.  It's much the same with lists: they bypass __getitem__
and __setitem__ and go directly to their internal.

OTOH, I've written a few C types that deliberately go though slower
Python methods to allow overriding.  But that has to be deliberate (for
the most part); as Frederick said, most C classes don't do that.


Carl Banks




More information about the Python-list mailing list