Home > Software engineering >  Using a class for repeated lines in python
Using a class for repeated lines in python

Time:04-28

I have a code like this:

def func1():
   #initialize database
   #request to a url

def func2():
   #initialize database
   #some other codes 

def func3():
   #other codes

As you see, initializing database is repeated multiple times between my functions. I want to ask how I can I organize this code or how can using a class help?

CodePudding user response:

Something like this should do the job. Suppothing that the initialization of the database consist in creating a new connection and a cursor.

class ClassName:
    def __init__(self):
        #initialize database
        self.connection = something_to_connect
        self.cursor = self.connection.something_to_get_cursor()

    def func1(self):
       #Use self.connection and self.cursor
       #request to a url

    def func2(self):
       #Use self.connection and self.cursor
       #some other codes 

    def func3(self):
       #other codes

    def __del__(self):
       something_to_close_connection
  • Related