Method acting on arguements passed

Andrew Gwozdziewycz apgwoz at gmail.com
Fri May 5 09:38:26 EDT 2006


> 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
apgwoz at gmail.com
http://www.23excuses.com
http://ihadagreatview.org
http://and.rovir.us





More information about the Python-list mailing list