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:
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:
Thank you for helping out with my understanding.
In Python, instances are just another type of namespace, and defining an instance variable outside the class definition involves nothing more than adding an entry in the dictionary of names and values that defines the instance.
If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors. However, if you want the users of your class to initialize the final variable through a constructor, delay the initialization until the constructor.
Instance variables are used within the instance method. We use the instance method to perform a set of actions on the data/value provided by the instance variable. We can access the instance variable using the object and dot ( . ) operator.
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.
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. class Cat (): def __init__ (self): self.meow = "Meow!" def meow_bigger (self): self.roar = "Roar!"
This means that for each object of a class, the instance variable value is different. When we create classes in Python, instance methods are used regularly. we need to create an object to execute the block of code or action defined in the instance method. Instance variables are used within the instance method.
Defined outside of all the methods, class variables are, by convention, typically placed right below the class header and before the constructor method and other methods. Info: To follow along with the example code in this tutorial, open a Python interactive shell on your local system by running the python3 command.
In Python the __init__() method is called the constructor and is always called when an object is created. Syntax of constructor declaration : def __init__(self): # body of the constructor Types of constructors :
Why is it best practice to initialize the instance variable within the constructor?
Because it makes it easy to see at a glance all of the attributes of the class. If you initialize the variables in multiple methods, it becomes difficult to understand the complete data structure without reading every line of code.
Initializing within the __init__
also makes documentation easier. With your example, you can't write "an instance of Cat has a roar
attribute". Instead, you have to add a paragraph explaining that an instance of Cat might have a "roar" attribute, but only after calling the "meow_louder" method.
Clarity is king. One of the smartest programmers I ever met once told me "show me your data structures, and I can tell you how your code works without seeing any of your code". While that's a tiny bit hyperbolic, there's definitely a ring of truth to it. One of the biggest hurdles to learning a code base is understanding the data that it manipulates.
What general/specific mess could arise if instance variables are regularly initialized in methods other than the constructor?
The most obvious one is that an object may not have an attribute available during all parts of the program, leading to having to add a lot of extra code to handle the case where the attribute is undefined.
In what scenarios would it be better to initialize instance variables in the other methods, rather than in the constructor?
I don't think there are any.
Note: you don't necessarily have to initialize an attribute with it's final value. In your case it's acceptable to initialize roar
to None
. The mere fact that it has been initialized to something shows that it's a piece of data that the class maintains. It's fine if the value changes later.
Remember that class members in "pure" Python are just a dictionary. Members aren't added to an instance's dictionary until you run the function in which they are defined. Ideally this is the constructor, because that then guarantees that your members will all exist regardless of the order that your functions are called.
I believe your example above could be translated to:
class Cat():
def __init__(self):
self.__dict__['meow'] = "Meow!"
def meow_bigger(self):
self.__dict__['roar'] = "Roar!"
>>> c = Cat() # c.__dict__ = { 'meow': "Meow!" }
>>> c.meow_bigger() # c.__dict__ = { 'meow': "Meow!", 'roar': "Roar!" }
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