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?
Answers:
Python allows you to add and delete attributes at any time. There are two problems with not doing it at __init__
- Your definitions aren’t all in one place
- 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
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?
Python allows you to add and delete attributes at any time. There are two problems with not doing it at __init__
- Your definitions aren’t all in one place
- 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