My questions concern instance variables that are initialized in methods outside the class constructor. This is for Python.
I'll first state what I understand:
- Classes may define a constructor, and it may also define other methods.
- 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.
An example of (2) and (3) -- see self.meow and self.roar in the Cat class below:
class Cat(): def __init__(self): self.meow = "Meow!" def meow_bigger(self): self.roar = "Roar!"
My questions:
Why is it best practice to initialize the instance variable within the constructor?
What general/specific mess could arise if instance variables are regularly initialized in methods other than the constructor? (E.g. Having read Mark Lutz's Tkinter guide in his Programming Python, which I thought was excellent, I noticed that the instance variable used to hold the PhotoImage objects/references were initialized in the further methods, not in the constructor. It seemed to work without issue there, but could that practice cause issues in the long run?)
In what scenarios would it be better to initialize instance variables in the other methods, rather than in the constructor?
To my knowledge, instance variables exist not when the class object is created, but after the class object is instantiated. Proceeding upon my code above, I demonstrate this:
>> c = Cat() >> c.meow 'Meow!' >> c.roar Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Cat' object has no attribute 'roar' >>> c.meow_bigger() >>> c.roar 'Roar!'
As it were:
- I cannot access the instance variable (c.roar) at first.
- However, after I have called the instance method c.meow_bigger() once, I am suddenly able to access the instance variable c.roar.
- Why is the above behaviour so?
Thank you for helping out with my understanding.