6

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?

1 Answer 1

9

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)
Sign up to request clarification or add additional context in comments.

1 Comment

If you use from pystrict import strict \n @strict \n class Firebird: ..., then it will be a runtime error to create attrs outside of init.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.