473,657 Members | 2,401 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Method acting on arguements passed

I want a class method to take action depending on the type of the
arguement passed to it.

ie:
getBook(id) # get the book by ID
getBook(name) # get the book by name
....

Other languages use the term function/method overloading to cope with
this. And when I googled about it seems that GvR is testing it for 3.0
inclusion or so.

I was thinking of right after the function declaration check for the
parameter passed by isinstance() or type() and use if..elif..else to
act.

Is this the pythonic way/best practice to apply here?

May 5 '06 #1
4 1309
Panos Laganakos wrote:
I want a class method to take action depending on the type of the
arguement passed to it.

ie:
getBook(id) # get the book by ID
getBook(name) # get the book by name
...

Other languages use the term function/method overloading to cope with
this. And when I googled about it seems that GvR is testing it for 3.0
inclusion or so.

I was thinking of right after the function declaration check for the
parameter passed by isinstance() or type() and use if..elif..else to
act.

Is this the pythonic way/best practice to apply here?


google for gnosis multimethods for a clean approach.
Diez
May 5 '06 #2
Panos Laganakos wrote:
I want a class method to take action depending on the type of the
arguement passed to it.

ie:
getBook(id) # get the book by ID
getBook(name) # get the book by name
...

Other languages use the term function/method overloading to cope with
this. And when I googled about it seems that GvR is testing it for 3.0
inclusion or so.

I was thinking of right after the function declaration check for the
parameter passed by isinstance() or type() and use if..elif..else to
act.

Is this the pythonic way/best practice to apply here?

I think the most Pythonic way is probably to have separate methods. You
presumably know at the point when you are calling getBook whether you have
an id or a name. So be explicit:

getBookById(id)
getBookByName(n ame)

This has the advantage that id and name could both be strings and the code
will still do the right thing. No amount of function overloading will
resolve arguments which have the same type but mean different things.

Another reasonable way to go is to use keyword arguments:

getBook(id=id)
getBook(name=na me)

which keeps down the number of different methods but could be confusing as
you have mutually exclusive keyword arguments.

Another option you might have here, if getBook does a lookup in a
dictionary, or database query, is simply to index the books by both id and
name. Then the definition might be:

def getBook(self, idorname):
return self._books[idorname]

and there is still no typechecking.

If you do feel you need typechecking, consider pulling it out into a
separate method so you are actually testing for the meaning of the
parameter rather than explicitly testing its type everywhere:

def getBook(self, idorname):
if self.isvalidid( idorname):
....
elif self.isvalidnam e(idorname):
....
else:
raise Oops()

May 5 '06 #3
Panos Laganakos wrote:
I want a class method to take action depending on the type of the
arguement passed to it.

ie:
getBook(id) # get the book by ID
getBook(name) # get the book by name
...

Other languages use the term function/method overloading to cope with
this. And when I googled about it seems that GvR is testing it for 3.0
inclusion or so.

I was thinking of right after the function declaration check for the
parameter passed by isinstance() or type() and use if..elif..else to
act.

Is this the pythonic way/best practice to apply here?


For simple case and if there's no need for extensibility, this is
usually quite enough - even if somewhat ugly. If the code for each case
is really different, I'd split the whole thing into three separate
methods : getBookById, getBookByName, and getBook that only do the
dispatch.

Else - and depending on the context, needs, specs and whatnot, I'd look
either at the visitor pattern (or any custom double-dispatch) or at an
existing multimethod implementation (like David Mertz's multimethod or
Philip Eby's protocol.dispat ch).

My 2 cents
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
May 5 '06 #4
> I want a class method to take action depending on the type of the
arguement passed to it.

ie:
getBook(id) # get the book by ID
getBook(name) # get the book by name


Keyword arguments are going to be the best solution, but you'll still
have to do checks like in this example which uses a generic keyword
and determines it's type..

def getBook(arg):
id = None
name = None
try:
id = int(arg)
# use the id here
except ValueError:
name = arg
# use name here

Now, if you were to use named arguments:
def getBook(id=None , name=None):
if id:
# do whatever for id
elif name:
# do whatever for name here

They are nearly identical.
---
Andrew Gwozdziewycz
ap****@gmail.co m
http://www.23excuses.com
http://ihadagreatview.org
http://and.rovir.us
May 5 '06 #5

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

Similar topics

12
1897
by: Donnal Walter | last post by:
The following method is defined in one of my classes: def setup(self, items={}): """perform setup based on a dictionary of items""" if 'something' in items: value = items # now do something with value if 'another' in items: value = items # do something else with value
5
36397
by: Andy | last post by:
Hi Could someone clarify for me the method parameter passing concept? As I understand it, if you pass a variable without the "ref" syntax then it gets passed as a copy. If you pass a variable with the "ref" syntax then it gets passed as a reference to the object and any changes to
6
2234
by: StephenMcC | last post by:
Hi All, Got a quick query in relation to the Server.Transfer method available in IIS 5+/ASP. I've got an issue where I want to take a portion of an online app and extract this out into a web site on its own, so I will end up having two web sites. This planned to aid problems we've been having with performance, as if the portion (which is an app in its own right) has problems we then have to restart the whole site and so bring everything...
9
1746
by: Ook | last post by:
I need a function that swaps arguements. This is my function. It works, after calling swapArgs aa now has 321, and bb has 123. My question - did I do it right? Just because it works doesn't mean I didn't make some fundamental mistake somewhere. void swapArgs( int &parm1, int &parm2 ); void swapArgs( int &parm1, int &parm2 ) { int zoot;
8
1859
by: Dawn Minnis | last post by:
Hey guys If I have a program (see codeSnippet1) that I compile to be called test.o Then run it as test.o n n 2 3 4 I want the code to be able to strip out the two characters at the start (always going to be 2) and store them as characters. But I can't seem to get it to work because it is a pointer to a vector of characters. However, if I only run with integer arguements and use codeSnippet2 it works fine and they convert nicely to...
0
336
by: JeffM | last post by:
If you've seen this before, sorry for the repost, the last post had no replies- and I'm still stuck. Can anyone suggest a way to use a comma delimited text file to supply arguements to a method call. Any ideas or sample code much appreciated. I am a tester learning C# so no amount of detail is too basic for me. Thanks in advance, Jeff
12
2677
by: Andrew Bullock | last post by:
Hi, I have two classes, A and B, B takes an A as an argument in its constructor: A a1 = new A(); B b = new B(a1);
3
22570
by: =?Utf-8?B?SmltSGVhdmV5?= | last post by:
I want to invoke a static method of a static class using a TEXT variable which has the namespace and class name which should be executed. I looked at the "CreateInstance" method, but this looks like a way to create an instance of a class, which is not what is needed. I attempted to use this method, even though I'm pretty sure that it is not applicable here and it fails as the "Type" variable is null after I use the following instruction:...
2
1812
by: Nike | last post by:
I have a small question w.r.t usage of default arguements in template.. I shall try to elaborate this with an example.. let's say I have some template function , where EntryType is the input for the template fn 1.. and another type where EntryType and lass P1 are both inputs.. case1 (1)template<class EntryType_> i.e void A<EntryType_>::createObject(EntryType::inputIdType inpId_ )..
0
8402
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, 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...
0
8315
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8734
jinu1996
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...
1
8508
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8608
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7341
agi2029
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...
1
6172
isladogs
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...
0
4323
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2733
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.