473,394 Members | 1,718 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Question about subclassing and overriding methods

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

Sep 7 '06 #1
4 1105

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

Sep 7 '06 #2
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
Why ???
but they are 3,4,9.
Yes, obviously.
I thought that getx in Test2 would override getx in Test,
It does.
even if getx
in Test has been replaced by getx2,
This "replacement" happens at instance initialisation time - ie, after
the class object have been created. If you don't want this to happen,
either skip the call to Test.__init__ in Test2.__init__, or make this
call with False as second param, or redefine getx2 in Test2. Or go for a
saner design...
but clearly that is not happening.
Can someone explain why.
Test2(2,True) calls Test2.__init__() with a Test2 instance 'self' and
y=True. Test2.__init__() then calls Test.__init__() with the same
instance and y=True. So the branch:
if y:
self.getx = self.getx2
is executed on the Test2 instance.

I don't see what puzzle you here.
Thanks

Frank Millman

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Sep 7 '06 #3

Bruno Desthuilliers wrote:
Frank Millman wrote:

This "replacement" happens at instance initialisation time - ie, after
the class object have been created. If you don't want this to happen,
either skip the call to Test.__init__ in Test2.__init__, or make this
call with False as second param, or redefine getx2 in Test2. Or go for a
saner design...
Thanks, Bruno, you gave me the clue to a less ugly workaround.

In my particular case, when I do subclass Test, y is always True.
Therefore I can rewrite it like this -

class Test2(Test):
def __init__(self,x):
Test.__init__(self,x,True)
def getx2(self):
print x*3

As you suggested, I redefine getx2 instead of getx, and it works as I
want.

Slightly less insane, I hope ;-)

Frank

Sep 7 '06 #4

Dennis Lee Bieber wrote:
On 7 Sep 2006 01:33:30 -0700, "Frank Millman" <fr***@chagford.com>
declaimed the following in comp.lang.python:
In my particular case, when I do subclass Test, y is always True.
Therefore I can rewrite it like this -

class Test2(Test):
def __init__(self,x):
Test.__init__(self,x,True)
def getx2(self):
print x*3

As you suggested, I redefine getx2 instead of getx, and it works as I
want.

Slightly less insane, I hope ;-)

I do hope this is just a simplified example <G>

Otherwise I'd have implemented it the other way around -- don't
compute the value on each get, but rather on the initialization
Thanks for the reply, Dennis. In fact, my real requirement has got
nothing to do with computing a value. That was just a way of
illustrating my need to call a different version of a method depending
on certain factors.

I have since come up with a different approach, which I have explained
in a new thread. It is still a bit complicated, so I would still
appreciate any comments on how to simplify it.

Frank

Sep 8 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Peter Olsen | last post by:
I want to define a class "point" as a subclass of complex. When I create an instance sample = point(<arglist>) I want "sample" to "be" a complex number, but with its real and imaginary...
8
by: Massimiliano Alberti | last post by:
Can I specialize a template function in a subclass without overriding it? (the main template function is defined in a base class). Now I'm doing something like that: (in base class)...
4
by: Tony | last post by:
I am in the process of setting up a base page model for multiple reasons. One of the reasons is so that I can catch all exceptions when derived pages throw/raise them. I don't want to use the...
6
by: Peter Oliphant | last post by:
I just discovered that the ImageList class can't be inherited. Why? What could go wrong? I can invision a case where someone would like to add, say, an ID field to an ImageList, possible so that...
5
by: craig | last post by:
I have am working on an app that has many forms. I would like to make each of these forms capable of interacting with the Windows Clipboard. I did some research and found out how to do this using...
6
by: tshad | last post by:
I am playing with Inheritance and want to make sure I understand it. I have the following Classes: ******************************************* Public Class AuthHeader:Inherits SoapHeader Public...
7
by: Steve Long | last post by:
Hello, I have a design question that I'm hoping someone can chime in on. (I still using VS 2003 .NET 1.1 as our company has not upgraded XP to sp2 yet. duh I know, I know) I have a class I wrote...
10
by: Frank Millman | last post by:
Hi all I recently posted a question about subclassing. I did not explain my full requirement very clearly, and my proposed solution was not pretty. I will attempt to explain what I am trying to...
16
by: manatlan | last post by:
I've got an instance of a class, ex : b=gtk.Button() I'd like to add methods and attributes to my instance "b". I know it's possible by hacking "b" with setattr() methods. But i'd like to do...
2
by: Kirk Strauser | last post by:
I want to subclass list so that each value in it is calculated at call time. I had initially thought I could do that by defining my own __getitem__, but 1) apparently that's deprecated (although I...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.