473,394 Members | 1,841 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.

overriding methods - two questions

Hi,
Here's a framework for the questions:

--- In a module, part of an API ---
class Basis ( object ):
def foo ( self, arg ):
pass

--- In user's own code ---
class Child ( Basis ):
def foo ( self, not, sure ):
...
Question 1:

Given that the user of the API can choose to override foo() or not, how can
I control the signature that they use? In the example the user has chosen
bad arguments and Python will complain, but it's describing the sig of the
*overridden* method and not the one in the parent class.

Is there some way I can control the error message to make it clear to the
user that they are using the signature of foo() incorrectly?

Question 2:

Say I am in class Basis, doing a loop and I have a list of Child objects. I
want to run the foo() method for each one that *has* a foo() method. i.e.
user has done this:

class Sam ( Child ):
...
*Sam does not define foo()

class Judy ( Child ):
def foo ( self, arg ):
...
* Judy does define foo()

Instances of Sam and Judy have been put into the list (within the instance)
of Basis. I want Basis to detect that Judy has foo() and run it.

I can handle question 2 by using a flag that must be set by the user.
Something like:
class Judy ( child ):
def __init__( self ):
self.pleaseCallFoo = true

And now, Basis can check for that var and only then call foo(), but this is
ugly and means more for the user to learn API-wise.

Any ideas?
/d
Nov 16 '07 #1
17 1665
On Nov 16, 11:03 am, Donn Ingle <donn.in...@gmail.comwrote:
Hi,
Here's a framework for the questions:

--- In a module, part of an API ---
class Basis ( object ):
def foo ( self, arg ):
pass

--- In user's own code ---
class Child ( Basis ):
def foo ( self, not, sure ):
...

Question 1:

Given that the user of the API can choose to override foo() or not, how can
I control the signature that they use? In the example the user has chosen
bad arguments and Python will complain, but it's describing the sig of the
*overridden* method and not the one in the parent class.
Actually, Python is complaining about your user's poor choice of
argument names. 'not' is a reserved keyword. Change it to 'naught' or
'knot' or 'not_' and Python will accept this just fine.

Whether this is a good idea or not is a separate question. But given
Python's philosophy of "you are the human, so you must know what you
are doing" (which is both an assumption and a directive), I don't
think you will find much language machinery to prevent it.

-- Paul
-- Paul
Nov 16 '07 #2
Donn Ingle:
Say I am in class Basis, doing a loop and I have a list of Child objects. I
want to run the foo() method for each one that *has* a foo() method.
This may help (on an old Python version):
>>class Sam: pass
....
>>class Judy:
.... def foo(self): pass
....
>>children = [Sam(), Judy(), Sam()]
for child in children: hasattr(child, "foo")
....
False
True
False

Bye,
bearophile
Nov 16 '07 #3
Actually, Python is complaining about your user's poor choice of
argument names. 'not' is a reserved keyword.
My example was poor, but my actual test code did't use 'not'. Python simply
checks the use of foo() to the local sig of foo() and does not go up the
chain. This is understandable and your next answer is more-or-less what I
was expecting.
Python's philosophy of "you are the human, so you must know what you
are doing" (which is both an assumption and a directive), I don't
think you will find much language machinery to prevent it.
Yeah. I guess I was hoping there'd be some clever trick to do it.

/d

Nov 16 '07 #4
Donn Ingle a écrit :
Hi,
Here's a framework for the questions:

--- In a module, part of an API ---
class Basis ( object ):
def foo ( self, arg ):
pass

--- In user's own code ---
class Child ( Basis ):
def foo ( self, not, sure ):
...
Question 1:

Given that the user of the API can choose to override foo() or not, how can
I control the signature that they use?
While technically possible (using inspect.getargspec), trying to make
your code idiot-proof is a lost fight and a pure waste of time.
Question 2:

Say I am in class Basis, doing a loop and I have a list of Child objects. I
want to run the foo() method for each one that *has* a foo() method. i.e.
user has done this:

class Sam ( Child ):
...
*Sam does not define foo()

class Judy ( Child ):
def foo ( self, arg ):
...
* Judy does define foo()

Instances of Sam and Judy have been put into the list (within the instance)
of Basis. I want Basis to detect that Judy has foo() and run it.

I can handle question 2 by using a flag that must be set by the user.
Something like:
class Judy ( child ):
def __init__( self ):
self.pleaseCallFoo = true

And now, Basis can check for that var and only then call foo(), but this is
ugly and means more for the user to learn API-wise.
Indeed.
Any ideas?
Quite a few, but I don't have enough context to tell which one would be
the best - nor why you want to do such a thing. Anyway, the simplest is
to just check :

for child in self.childrens:
if 'foo' in child.__class__.__dict__:
child.foo()

but this won't call foo for :

class Dude(Judy):
pass

Don't know if that's what you want. If not (ie, you want to call
child.foo if foo is not Basis.foo), then:

for child in self.childrens:
if child.foo.im_func is not self.foo.im_func:
child.foo()

HTH
Nov 16 '07 #5
>This may help (on an old Python version):
>>>class Sam: pass
class Judy:
... def foo(self): pass
...
>>>children = [Sam(), Judy(), Sam()]
for child in children: hasattr(child, "foo")
...
False
True
False
That's not what my tests are showing. While Sam has no foo, it's coming from
(in my OP) Child (which is the parent class), so hasattr(Sam(),"foo") is
returning True.

/d

Nov 16 '07 #6
for child in self.childrens:
if 'foo' in child.__class__.__dict__:
child.foo()
Bruno, you're the man! I really must take the time to look into all those
under-under score things!

Thanks.

/d

Nov 16 '07 #7
Donn Ingle a écrit :
>for child in self.childrens:
if 'foo' in child.__class__.__dict__:
child.foo()
Bruno, you're the man! I really must take the time to look into all those
under-under score things!
Knowing Python's object model can help, indeed !-)

Now while this kind of stuff is ok in the low-level parts of a
framework, it shouldn't be seen too much in application code IMHO.
Nov 16 '07 #8
On Nov 16, 11:35 am, Donn Ingle <donn.in...@gmail.comwrote:
This may help (on an old Python version):
>>class Sam: pass
class Judy:
... def foo(self): pass
...
>>children = [Sam(), Judy(), Sam()]
for child in children: hasattr(child, "foo")
...
False
True
False

That's not what my tests are showing. While Sam has no foo, it's coming from
(in my OP) Child (which is the parent class), so hasattr(Sam(),"foo") is
returning True.

/d
But also in your OP: "I want to run the foo() method for each one that
*has* a foo() method ...." So hasattr(child, "foo") really does
answer the question as posed, even if it's not really what you want.
I am curious as to why you want to go through such contortions. What
do you gain. What happens, for example, if a subclass of Judy is
passed in that does not override foo? Should foo be called in that
case or not?

--Nathan Davis
Nov 16 '07 #9
On Fri, 16 Nov 2007 18:28:59 +0100, Bruno Desthuilliers wrote:
>Question 1:

Given that the user of the API can choose to override foo() or not, how
can I control the signature that they use?

While technically possible (using inspect.getargspec), trying to make
your code idiot-proof is a lost fight and a pure waste of time.

Worse: it's actually counter-productive!

The whole idea of being able to subclass a class means that the user
should be able to override foo() *including* the signature. Why do you
want to stop them? It's their subclass, not yours. You don't know what
arguments it needs.

Let me give a practical example: in mathematics there is a construct
known as a continued fraction. What it is isn't especially important, if
you're curious you can google for it. If you were defining a class for
continued fractions, you might do this:

class ContinuedFraction(object):
def __init__(self, list_of_numerators, list_of_denominators):
pass
# lots of other methods

cf = ContinuedFraction([3, 7, 2, 8, 9, 5], [2, 3, 1, 5, 3, 7])

If I wanted to subclass your ContinuedFraction class to provide regular
continued fractions, I could do this:

class RegularCF(ContinuedFraction):
def __init__(self, *denominators):
numerators = [1]*len(denominators)
super(RegularCF, self).__init__(numerators, denominators)
# all other methods are inherited from super-class without change

cf = RegularCF(4, 9, 1, 2, 6, 3)
But if you did what you're proposing to do, I couldn't do that. I'd need
to do something silly like this:

class RegularCF(ContinuedFraction):
def __init__(self, list_of_numerators, list_of_denominators):
numerators = [1]*len(list_of_denominators)
super(RegularCF, self).__init__(numerators, list_of_denominators)

cf = RegularCF(None, [4, 9, 1, 2, 6, 3])
just so that the signatures matched. What a waste of time.

And worse, what if my subclass needed *more* arguments than your
signature provided? The hoops I would have to jump through would not only
be flaming, they'd be spinning and flying through the air, with rotating
knives and trip-wires.

--
Steven
Nov 16 '07 #10
>While technically possible (using inspect.getargspec), trying to make
>your code idiot-proof is a lost fight and a pure waste of time.
Worse: it's actually counter-productive!
The whole idea of being able to subclass a class means that the user
should be able to override foo() *including* the signature.
Steven,
In this case, the def in question is named Draw. It's args are context and
framenumber. The body is 'pass'. I want users to use the exact signature
(but they can change the varnames to suit) because the draw() method is
*not* being called by the user but *by* my API (in a timeout loop).

So, my API is sending blah.Draw( cairo.context, currentFrame ) *to* the
user's own object.Draw.Thereafter, whatever Cairo drawing commands they use
in their override of Draw() is what gets drawn -- if that makes sense :)

I guess that's the long way of saying it's a call-back function :)

So, I'm trying to guarantee that they don't mess with it to make life easier
for them. As Bruno has mentioned, this is up to the human and so it'll be a
rule in the docs instead.

/d

Nov 17 '07 #11
I am curious as to why you want to go through such contortions. Â*What
do you gain.
for obj in list:
if obj has a foo() method:
a = something
b = figureitout ( )
object.foo ( a, b )

I am accepting objects of any class on a stack. Depending on their nature I
want to call certain methods within them. They can provide these methods or
not.
What happens, for example, if a subclass of Judy is
passed in that does not override foo? Â*Should foo be called in that
case or not?
No.

Bruno has given me a good solution:

for obj in list:
if 'foo' in obj.__class__.__dict__:
etc.

Although I am concerned that it's a loop ('in') and so may be slower than
some other way to detect foo().

So, that's the story.

/d

Nov 17 '07 #12
En Sat, 17 Nov 2007 01:56:22 -0300, Donn Ingle <do********@gmail.com>
escribió:
for obj in list:
if 'foo' in obj.__class__.__dict__:
etc.

Although I am concerned that it's a loop ('in') and so may be slower than
some other way to detect foo().
'in' for dictionaries is fast and runs in constant time. You may be
thinking about 'in' for lists, that runs in time proportional to the
number of elements.

--
Gabriel Genellina

Nov 17 '07 #13
Donn Ingle wrote:
>I am curious as to why you want to go through such contortions. Â*What
do you gain.
for obj in list:
if obj has a foo() method:
a = something
b = figureitout ( )
object.foo ( a, b )

I am accepting objects of any class on a stack. Depending on their nature I
want to call certain methods within them. They can provide these methods or
not.
>What happens, for example, if a subclass of Judy is
passed in that does not override foo? Â*Should foo be called in that
case or not?
No.
Hmm, you are missing the point of inheritance. Behaviour not
meant to be shared by all subclasses should not be implemented in
the base class, i. e. either Sam should not inherit from Child or Child
should not implement foo().

However, here is another hack to hide an inherited method:
>>class Child(object):
.... def foo(self): print "Child's foo"
.... def __str__(self): return self.__class__.__name__
....
>>class Sam(Child):
.... @property
.... def foo(self): raise AttributeError
....
>>class Judy(Child):
.... def foo(self): print "Judy's foo"
....
>>for item in [Sam(), Judy()]:
.... try:
.... foo = item.foo
.... except AttributeError:
.... print "no foo for", item
.... else:
.... foo()
....
no foo for Sam
Judy's foo

If you find try ... except too verbose -- it works with hasattr(), too.
Bruno has given me a good solution:

for obj in list:
if 'foo' in obj.__class__.__dict__:
etc.

Although I am concerned that it's a loop ('in') and so may be slower
than some other way to detect foo().
__dict__ is a dictionary (who would have thought), the "in" operator
therefore does not trigger a loop and is very fast.

Peter
Nov 17 '07 #14
Thanks, good tips all-round. I have it working okay at the moment with all
the suggestions. It may break in future, but that's another day :)
/d

Nov 17 '07 #15
Steven D'Aprano a écrit :
On Fri, 16 Nov 2007 18:28:59 +0100, Bruno Desthuilliers wrote:
>>Question 1:

Given that the user of the API can choose to override foo() or not, how
can I control the signature that they use?
While technically possible (using inspect.getargspec), trying to make
your code idiot-proof is a lost fight and a pure waste of time.


Worse: it's actually counter-productive!

The whole idea of being able to subclass a class means that the user
should be able to override foo() *including* the signature.
If you see subclassing as subtyping, the signatures should always stay
fully compatibles.

Nov 19 '07 #16
On Mon, Nov 19, 2007 at 01:41:46PM +0100, Bruno Desthuilliers wrote regarding Re: overriding methods - two questions:
>
Steven D'Aprano a ?crit :
On Fri, 16 Nov 2007 18:28:59 +0100, Bruno Desthuilliers wrote:
>Question 1:

Given that the user of the API can choose to override foo() or not, how
can I control the signature that they use?
While technically possible (using inspect.getargspec), trying to make
your code idiot-proof is a lost fight and a pure waste of time.

Worse: it's actually counter-productive!

The whole idea of being able to subclass a class means that the user
should be able to override foo() *including* the signature.

If you see subclassing as subtyping, the signatures should always stay
fully compatibles.
Isn't that more what Zope-type interfaces are for than inheritance? I'm uncertain here, but I'm not persuaded that changing signature is bad.
Nov 19 '07 #17
J. Clifford Dyer a écrit :
On Mon, Nov 19, 2007 at 01:41:46PM +0100, Bruno Desthuilliers wrote regarding Re: overriding methods - two questions:
>Steven D'Aprano a ?crit :
>>On Fri, 16 Nov 2007 18:28:59 +0100, Bruno Desthuilliers wrote:

Question 1:
>
Given that the user of the API can choose to override foo() or not, how
can I control the signature that they use?
While technically possible (using inspect.getargspec), trying to make
your code idiot-proof is a lost fight and a pure waste of time.

Worse: it's actually counter-productive!

The whole idea of being able to subclass a class means that the user
should be able to override foo() *including* the signature.
If you see subclassing as subtyping, the signatures should always stay
fully compatibles.

Isn't that more what Zope-type interfaces are for than inheritance?
With dynamically typed languages like Python, you don't need any formal
mechanism (zope-like interface or whatever) for subtyping to work - just
make sure your two classes have the same public interface and it's ok.
So indeed inheritance is first a code-reuse feature.
I'm uncertain here, but I'm not persuaded that changing signature is
bad.
Depends if the subclass is supposed to be a proper subtype (according to
LSP) too.
Nov 19 '07 #18

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

Similar topics

3
by: Andrew Durdin | last post by:
In Python, you can override the behaviour of most operators for a class, by defining __add__, __gt__, and the other special object methods. I noticed that, although there are special methods for...
3
by: Ali Eghtebas | last post by:
Hi, I have 3 questions regarding the code below: 1) Why can't I trap the KEYDOWN while I can trap KEYUP? 2) Is it correct that I use Return True within the IF-Statement? (I've already read...
5
by: Hongzheng Wang | last post by:
Hi, I have a problem about the overriding of private methods of base class. That is, if a method f() of base class is private, can the derived class overriding f() be overriding? For...
5
by: zero | last post by:
I'm having trouble with overriding methods in subclasses. I'll explain the problem using some code: class BaseClass { protected: void method2(); public: void method1();
4
by: Rafael Veronezi | last post by:
I have some questions about override in inheritance, and virtual members. I know that you can you override a method by two ways in C#, one, is overriding with the new keyword, like: public new...
4
by: ORi | last post by:
Hi all ! There's a question I've been bothering for a while: I'm actually developing architectural frameworks for application developing and I think virtual methods, although needed because of...
2
by: ESPNSTI | last post by:
Hi, I'm very new to C# and .Net, I've been working with it for about a month. My experience has been mainly with Delphi 5 (not .Net). What I'm looking for is for a shortcut way to override a...
17
by: Bob Weiner | last post by:
What is the purpose of hiding intead of overriding a method? I have googled the question but haven't found anything that makes any sense of it. In the code below, the only difference is that...
10
by: r035198x | last post by:
The Object class has five non final methods namely equals, hashCode, toString, clone, and finalize. These were designed to be overridden according to specific general contracts. Other classes that...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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.