why is defining an object variable outside of __init__ frowned upon?

Question:

I sometimes define an object variable outside of __init__. plint and my IDE (PyCharm) complain.

class MyClass():
    def __init__(self):
        self.nicevariable = 1   # everyone is happy

    def amethod(self):
        self.uglyvariable = 2   # everyone complains

plint output:

W:  6, 8: Attribute 'uglyvariable' defined outside __init__ (attribute-defined-outside-init)

Why is this a incorrect practice?

Asked By: WoJ

||

Answers:

Python allows you to add and delete attributes at any time. There are two problems with not doing it at __init__

  1. Your definitions aren’t all in one place
  2. If you use it in a function, you may not have defined it yet

Note that you can fix the above problem of setting an attribute later by defining it in __init__ as:

self.dontknowyet = None      # Everyone is happy
Answered By: stark
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.