Question about subclassing and overriding methods
Frank Millman
frank at chagford.com
Thu Sep 7 03:56:13 EDT 2006
Frank Millman wrote:
> 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.
>
Ok, on reflection I more or less understand what is happening, and I
have found an ugly workaround -
class Test2(Test):
def __init__(self,x,y=False):
getx = self.getx
Test.__init__(self,x,y)
self.getx = getx
def getx(self):
print self.x*3
Test2(1).getx()
Test2(2,True).getx()
Test2(3).getx()
Now I get 3,6,9 as intended.
I would still appreciate any comments, especially if someone can
suggest a better approach.
Thanks
Frank
More information about the Python-list
mailing list