U
U
usgleb2011-11-25 13:32:40
Python
usgleb, 2011-11-25 13:32:40

Convenient extension of class functionality

I write in Python. Faced such task — there is a class for operation with a database. It has some features. One gets the first 50 records, the second saves the record and returns some parameter, the third gets the record, and so on. To work, I create 1 instance of this class and set a reference to it in all objects, and they refer to this class by reference and thus gain access to its functions.

class DB():
    def __init__(self):
        #Какие-то настройки для создания соединения с БД

    def createConnection(self):
        #Создание соединения
        self.connection = new Connection(param1, param2, param3)

    def get50Records(self):
        #Получение 50 записей
        result = self.conncetion.select(TABLE_RECORDS, limit=50)
        return result

    def saveRecords(self, params):
        pass

     ....



What is the problem - when I want to add a new function to the DB class, I have to add it to the class itself. That is, how to change it. And you don't want to do it. We need some convenient way to add new functionality.

I came up with this. I'm creating one DB class that only has parameters for creating a connection and the connection creation function itself. Next, I create a new class, I call it, for example, DBget50Records and there is the functionality of the get50Records function. And I inherit the DB class from the DBget50Records class. That is, it turns out that DBget50Records is the parent and the DB class has all the functionality that the parent has. Therefore, I also create 1 instance of the DB class and pass a link to it to all objects. And if I need to expand the functionality, then I create a new DBsaveRecords class and add it to the parents of the DB class.

class DBget50Records():

    def get50Records(self):
        #Получение 50 записей
        result = self.conncetion.select(TABLE_RECORDS, limit=50)
        return result

class DBsaveRecords():

    def saveRecords(self, params):
        pass

class DB(DBget50Records, DBsaveRecords):
    def __init__(self):
        #Какие-то настройки для создания соединения с БД

    def createConnection(self):
        #Создание соединения
        self.connection = new Connection(param1, param2, param3)


What do you think about this? I understand that everything will have to change the DB class by adding parents to it, but so far I haven’t come up with anything more interesting. Pattern Decorator is not suitable!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
simplecode, 2011-11-25
@simplecode

If I were you, I would read Butch ...
Why such difficulties?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question