Class vs Instance Variables
Class Variables
Class variables are shared among all instances of a class. They are associated with the class rather than any particular instance.
- Declared outside of any method in the class.
- Found at top level of the class definition.
class ClassName:
''' Optional docstring '''
# Class variables defined here
class_var1 = value1
...
def __init__(self, attribute1, ...):
self.attribute1 = attribute1
...
...
Instance Variables
Instance variables are specific to each instance of a class. Each instance has its own set of instance variables.
- Declared within the
__init__constructor method or any other method of the class - Accessed using the
selfkeyword within methods. - Used to store data that varies between instances.
class ClassName:
''' Optional docstring '''
# Class variables defined here
class_var1 = value1
...
def __init__(self, attribute1, ...): # defining instance variables
self.attribute1 = attribute1
...
...