user6739366
user6739366

Reputation:

"This inspection detects instance attribute definition outside __init__ method" PyCharm

I'm using the following class to connect and create a cursor within a firebase database:

class Firebird:

    username= "..."
    password= "..."

    def __init__(self, archive):
        self.archive = archive

   def connect(self):
       try:
           self.connection = connect(dsn=self.archive, user=self.username, password=self.password)
       except Error, e:
           print "Failed to connect to database", e
           exit(0)

And the PyCharm is warning me: "This inspection detects instance attribute definition outside init method", in the self.connection assign.

Is it a bad practice assign properties to the instance outside of __init__? In this case, what could i do?

Upvotes: 6

Views: 9135

Answers (1)

Antoine
Antoine

Reputation: 4029

Yes it's generally considered a good practice to explicitly define/declare all your attributes in the __init__ function, this way you have a quick list of all used (or unused) attributes in the class.

class Firebird:

    username= "..."
    password= "..."

    def __init__(self, archive):
        self.archive = archive
        self.connection = None

   def connect(self):
       try:
           self.connection = connect(dsn=self.archive, user=self.username, password=self.password)
       except Error, e:
           print "Failed to connect to database", e
           exit(0)

Upvotes: 9

Related Questions