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.pleaseCall Foo = 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 17 1683
On Nov 16, 11:03 am, Donn Ingle <donn.in...@gma il.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
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
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
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.getargs pec), 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.pleaseCall Foo = 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_fu nc is not self.foo.im_fun c:
child.foo()
HTH
>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
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
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.
On Nov 16, 11:35 am, Donn Ingle <donn.in...@gma il.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
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.getargs pec), 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 ContinuedFracti on(object):
def __init__(self, list_of_numerat ors, list_of_denomin ators):
pass
# lots of other methods
cf = ContinuedFracti on([3, 7, 2, 8, 9, 5], [2, 3, 1, 5, 3, 7])
If I wanted to subclass your ContinuedFracti on class to provide regular
continued fractions, I could do this:
class RegularCF(Conti nuedFraction):
def __init__(self, *denominators):
numerators = [1]*len(denominato rs)
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(Conti nuedFraction):
def __init__(self, list_of_numerat ors, list_of_denomin ators):
numerators = [1]*len(list_of_de nominators)
super(RegularCF , self).__init__( numerators, list_of_denomin ators)
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 most operators,
they are conspicuously absent for the logical "or" and "and". I'm
guessing that the reason for this is that these operators
short-circuit if their first operand answers the whole question?
Would it be possible to allow...
|
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 the documentation but it is rather hard to understand so please
don't refer to it :)
3) Many examples in the newsgroups use Return MyBase.ProcessKeyPreview(m) as
the last code line while I have used Return MyBase.ProcessKeyEventArgs(m)
|
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 example,
class base {
|
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();
|
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 bool Equals(object obj) {}
Another is using the override keyword, like:
public override bool Equals(object obj) {}
| |
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 the
flexibility they introduce (flexibility really needed in framework
developing), are often a nuisance for final developers. They don't
like them because they never know if base class must be called and
where should they place the call if...
|
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 property without actually having to reimplement the get and set methods.
In other words, override the the property without changing the functionality of the base property and without explicitly having to reimplement the get and set methods to make it do...
|
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 when the Poodle is upcast to
the Dog (in its wildest dreams) it then says "bow wow" where the bernard
always says "woof" (see code). Basically, it appears that I'm hiding the
poodle's speak method from everything except the poodle.
Why would I...
|
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 make use of these methods assume that the methods obey these contracts so it is necessary to ensure that if your classes override these methods, they do so correctly.
In this article I'll take a look at the equals and hashCode methods.
...
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
| |
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |