简体   繁体   English

在__init__内部调用类方法

[英]Call class method inside __init__

I want to call the method connect() in my __init__() method inside my class db_connector() . 我想在类db_connector() __init__()方法中调用方法connect() 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() . 我还尝试__init__()connect()切换位置,所以__init__()connect()之上-但是在这种情况下,他甚至找不到方法connect()

Ideas? 想法?

Calling another method from your __init__ is fine and not the cause of your problems here. __init__调用另一个方法很好,而不是造成问题的原因。 Instead, you somehow misspelled the __init__ method, and creating an instance ends up calling object.__init__ instead. 相反,您以某种方式拼写了__init__方法,并创建了一个实例,最终调用了object.__init__

Double-check the spelling of the method, and make sure it is indented correctly to be part of the db_connector class definition. 仔细检查该方法的拼写,并确保将其正确缩进以包含在db_connector类定义中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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