简体   繁体   中英

What is the pythonic way for method overloading?

Currently I'm focussing on the pythonic way of writing my code and I ran into two situations where I wonder what's best.

First the situation for method overloading, which is not available in python. How would I best solve the situation where I have a function that fetches data from a database, however depending on an argument being an integer or a list of integers the query would be different. Example:

def getData(ids):
    if type(ids) == int:
        # query the database in an efficient manner for a single ID
    elif type(ids) is list:
        # query the database in a different manner efficiently for multiple ID's
        # also return the data differently

Would I do all the work in a single function or do I use different functions which are called from the above function to do the work? Or would I just need to call a different function explicitly depending on whether I have a list of ID's or just a single ID? What do you believe is best?

Use isinstance :

import collections

def getData(ids):
    if isinstance(ids, collections.Iterable):
        # query the database efficiently for multiple ID's
    else:
        # query the database in an efficient manner for a single ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM