Instance Variables
As a general rule, it is best to initialize all of the instance variables in the __init__() function for consistency.
As a general rule, it is best to initialize all of the instance variables in the __init__() function for consistency.
The data held by an object is referred to as an instance variable. Instance variables aren't shared by all instances of a class — they are variables that are specific to the object they are attached to.
Let's say that we have the following class definition:
We've learned so far that a class is a schematic for a data type and an object is an instance of a class, but why is there such a strong need to differentiate the two if each object can only have the methods and class variables the class has?
This is because each instance of a class can hold different kinds of data.
If an instance variable is not set in __init__() can it be referenced by a class method?
Yes, the instance variable can be referenced by a class method using self so long as it has been set before the call. If not, an AttributeError will be generated.