Introduction
Note that both Class Attributes, and Class Variables are both interchange, and they both refers to the same things
When we design a class attributes, we use instance variables and class variables.
In Class, attributes can be defined into two parts:
- Class Variables
- Instance variables
Instance Variables vs. Class Variables in Python
When designing a class in Python, we work with attributes (data stored in objects). These attributes fall into two categories:
- Instance Variables (specific to each object/instance).
- Class Variables (shared across all instances of the class).
Class Variables
Definition
- Class variables are shared across all objects of a class.
- Defined inside the class body, but outside of any methods.
- Only one copy exists, and all instances refer to the same variable.
Key Characteristics
- Belong to the class itself, not individual objects.
- Defined directly in the class body (without
self). - Any change to a class variable affects all objects (unless overridden at the instance level).
- Often used for constants, counters, or shared properties.
Instance Variables
Definition
- Instance variables are unique to each object created from a class.
- They are defined inside the constructor (
__init__()method) or other instance methods using the keywordself. - Each object has its own copy of instance variables.
Key Characteristics
- Belong to one object only.
- Defined with the prefix
self.. - Values can differ across instances of the class.
- Can be modified for each object without affecting others.
‣
Python Class Variables
‣