Skip to content
Advertisement

python function parameter control

def getBooks(self,name):
        query = "SELECT * FROM books"
        self.cursor.execute(query)
        books = self.cursor.fetchall()
        return books

I have a function called “getBooks”, and this function is actually a combination of 2 functions. one function must work without taking the ‘name’ parameter, the other must work by taking the ‘name’ parameter because i have to change the sql template according to the ‘name’ parameter. how can i provide that?

Advertisement

Answer

You can specify a default parameter of name to be None, and then treat the variable according to its type:

def getBooks(self,name=None):
    if name is None:
        ...
    else:
        ...

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement