19

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?

WoJ
  • 23,237
  • 42
  • 145
  • 273

1 Answers1

24

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 definin it in __init__ as:

self.dontknowyet = None      # Everyone is happy
stark
  • 11,447
  • 3
  • 32
  • 46
  • So it's not unlike how JSLint/JSHint want you to move all your variable declarations to the beginning of their respective functions? – RevanProdigalKnight Aug 06 '14 at 11:25
  • (1) relates to you and more important to everyone also trying to use your code. Be kind, make nice code and put definitions in one place – RvdK Aug 06 '14 at 11:25
  • 8
    The important point being that it makes it much easier to reason about your code. Generally when we think of objects, we thing of a thing with a given set of attributes on it. Having to remember the circumstances under which some of those attributes appear leads to more potential bugs and a harder thing to work with. – Gareth Latty Aug 06 '14 at 11:41