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?
It is perfectly possible for instance attributes to be defined outside of your __init__ , you need to be careful about how your class is used.
Instance variables are generally defined/initialized within the constructor. But instance variables can also be defined/initialized outside the constructor, e.g. in the other methods of the same class.
Python instance variables can have different values across multiple instances of a class. Class variables share the same value among all instances of the class. The value of instance variables can differ across each instance of a class. Class variables can only be assigned when a class has been defined.
What is an Instance Variable in Python? If the value of a variable varies from object to object, then such variables are called instance variables. For every object, a separate copy of the instance variable will be created. Instance variables are not shared by objects.
Python allows you to add and delete attributes at any time. There are two problems with not doing it at __init__
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With