jwi
jwi

Reputation: 1178

Call class method inside __init__

I want to call the method connect() in my __init__() method inside my class db_connector().

Here's my code so far:

class db_connector(object):

   def connect(self, db_data):

       try:
           self.__con = psycopg2.connect(database = db_data['dbname'], user = db_data['user'])
           self.__cur = self.__con.cursor()
           logging.info(" Successfully connected to db.")
           return True

       except psycopg2.DatabaseError:
           logging.exception(" Error while connecting to db. Maybe check your login-data.")
           return False

   def __init__(self, db_data):

       self.__con = None
       self.__cur = None

       if self.__con:
           self.connect(db_data)

I get:

TypeError: object() takes no parameters

I've also tried switching positions from __init__() and connect(), so __init__() is over connect() - but in this case, he can't even find the method connect().

Ideas?

Upvotes: 0

Views: 1780

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124718

Calling another method from your __init__ is fine and not the cause of your problems here. Instead, you somehow misspelled the __init__ method, and creating an instance ends up calling object.__init__ instead.

Double-check the spelling of the method, and make sure it is indented correctly to be part of the db_connector class definition.

Upvotes: 1

Related Questions