How to use arguments if they are not used elsewhere than in the __init__ method of a class?

4079 views python
2

I'm writing a class for MySQL connection wih mysql.connector module. I pass some arguments to the class, to connect and act on the database.

What is the best practice, to use arguments in class, if they are not use elsewhere than in __init__ definition?

This:

class Database:
    def __init__(self, db_host, db_port, db_database, db_user, db_password):        
        self.host = db_host
        self.port = db_port
        self.database = db_database
        self.user = db_user
        self.password = db_password

        self._conn = mysql.connector.connect(
            host = self.host,
            port = self.port,
            database = self.database,
            user = self.user,
            password = self.password)

or this:

class Database:
    def __init__(self, db_host, db_port, db_database, db_user, db_password):        

        self._conn = mysql.connector.connect(
            host = db_host,
            port = db_port,
            database = db_database,
            user = db_user,
            password = db_password)

answered question

1 Answer

10

If you don't use the constructor's argument for anything other than establishing the connection and do not intend to expose them to users of this class for any reason, there's no need to save them to members - go with the second approach.

posted this

Have an answer?

JD

Please login first before posting an answer.