shahriar Dehghani
shahriar Dehghani

Reputation: 59

Can we call two function after each other from a class in python

class admin():
    query = ''
    table = ''
    def __init__(self):
        constr = sqlite3.connect('meta.db')
        cur = constr.cursor()
        self.cur = cur
    def select(self, table):
        self.table = table
        query = "select * from {table}".format(table=self.table)
        # query = "select * from user"
        result = self.cur.execute(query)
        result = result.fetchall()
        return result
    def orderby(self, field):
        query += "ORDER BY {table}.{field} ASC".format(table=self.table,field=self.field)
        return query

This is my code.
what I want is calling a function after another function

mydb = admin()
mydb.select('usettable').orderby('id')

mydb is a contractor for the admin class and I want to call two functions of this class after each other.

Upvotes: 1

Views: 235

Answers (1)

Benyamin Jafari
Benyamin Jafari

Reputation: 33986

I think you are looking for something like this:

In [12]: class A:
    ...:     def foo(self, msg):
    ...:         self.msg = msg
    ...:         print(msg)
    ...:         return self
    ...:     def bar(self, name):
    ...:         print(self.msg, name)
In [13]: a = A()
In [14]: a.foo("Hi")                              
Hi
In [15]: a.foo("Hi").bar("Shahriar")
Hi
Hi Shahriar

So, in your case, it might be as follows:

class Admin:
    def __init__(self):
        constr = sqlite3.connect('meta.db')
        cur = constr.cursor()
        self.cur = cur
    def select(self, table):
        self.table = table
        self.query = "select * from {}".format(self.table)
        return self
    def orderby(self, field):
        self.query += "ORDER BY {}.{} ASC".format(self.table, field)
        return self
    def execute(self):
        result = self.cur.execute(self.query)
        result = result.fetchall()
        return result

Test:

mydb = admin()
mydb.select('usettable').orderby('id').execute()

Upvotes: 1

Related Questions