Question about subclassing and overriding methods

Frank Millman frank at chagford.com
Thu Sep 7 03:38:05 EDT 2006


Hi all

Assume a simple class -

class Test(object):
    def __init__(self,x):
        self.x = x
    def getx(self):
        print self.x

Test(1).getx()
Test(2).getx()
Test(3).getx()

As expected, the results are 1,2,3

Assume a slight variation, where given a particular condition I want a
particular method to behave differently. I know that I could subclass,
but for various reasons I preferred to do it this way -

class Test(object):
    def __init__(self,x,y=False):
        self.x = x
        if y:
            self.getx = self.getx2
    def getx(self):
        print self.x
    def getx2(self):
        print self.x * 2

Test(1).getx()
Test(2,True).getx()
Test(3).getx()

As expected, the results are 1,4,3

Now assume a subclass of the above class, where I want the method to
behave diferently again -

class Test2(Test):
    def __init__(self,x,y=False):
        Test.__init__(self,x,y)
    def getx(self):
        print self.x*3

Test2(1).getx()
Test2(2,True).getx()
Test2(3).getx()

Here I was hoping that the results would be 3,6,9 but they are 3,4,9.

I thought that getx in Test2 would override getx in Test, even if getx
in Test has been replaced by getx2, but clearly that is not happening.
Can someone explain why.

Thanks

Frank Millman




More information about the Python-list mailing list