If an instance variable is not set in __init__() can it be referenced by a class method?


#1

Question

If an instance variable is not initialized in the __init__() function, can it still be referenced by a class method?

Answer

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. As a general rule, it is best to initialize all of the instance variables in the __init__() function for consistency.


#2

__init__() is what defines instance variables. Any other is a class variable until an instance changes it within its own context, thereby adopting a new instance variable.


#3

They pyDocs have a good example of the difference between class and instance variables

“”"
instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:
“”"

class Dog:

    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind                  # shared by all dogs
'canine'
>>> e.kind                  # shared by all dogs
'canine'
>>> d.name                  # unique to d
'Fido'
>>> e.name                  # unique to e
'Buddy'