简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM