473,387 Members | 1,453 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,387 software developers and data experts.

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 1288
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(name)

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=name)

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.isvalidname(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.dispatch).

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.com
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
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...
5
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...
6
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...
9
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...
8
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...
0
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...
12
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
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...
2
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
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...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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,...

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.