Python Instance Variable: Usage and Scope Explained
Understand how instance variables work in Python, how they differ from class variables, and how to manage them correctly in your classes.

When you create an object from a class in Python, the data that belongs to that specific object is stored in instance variables. Understanding how instance variables work is essential for writing correct object-oriented code. An instance variable is data attached to a single object, not to the class itself. Each object has its own copy, and changes to one object's variable do not affect another object of the same class.
Instance Variables vs Class Variables
Instance variables are declared inside methods, typically __init__, using self. They are unique to each object. Class variables, on the other hand, are declared directly in the class body and are shared across all instances. The distinction matters because it determines whether a change affects one object or the entire class.
class Employee:
company = "Acme" # class variable
def __init__(self, name):
self.name = name # instance variableHere, company is shared by all Employee objects, while name is specific to each instance. If you assign a new value to employee1.company, it creates an instance variable that shadows the class variable for that object only, leaving other instances unchanged.
Declaring Instance Variables with init
The standard way to declare instance variables is inside the __init__ method. This ensures that every object gets its own set of attributes when created. You can also declare instance variables in other methods, but doing so can lead to objects without those attributes if the method is not called.
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
self.mileage = 0 # default valueUsing __init__ is recommended because it guarantees that the object is fully initialized after construction. If you assign an instance variable later in a separate method, you risk an AttributeError if the method is not invoked.
Accessing and Modifying Instance Variables
Instance variables are accessed and modified using dot notation. You can read and modify them directly from outside the class unless you use properties to control access.
car = Car("Toyota", "Corolla")
print(car.make) # Toyota
car.mileage = 5000
print(car.mileage) # 5000Python does not enforce private attributes. The convention is to prefix a name with an underscore (_name) to signal that it is internal. Double underscores trigger name mangling, which makes the attribute harder to access accidentally but does not make it truly private.
Common Pitfall: Mutable Default Arguments
A frequent mistake is using a mutable object as a default argument in a method definition. This is not specific to instance variables, but it often appears when you try to initialize an instance variable with a default list or dictionary.
class ShoppingCart:
def __init__(self, items=[]): # wrong
self.items = itemsThis creates a single list shared by all ShoppingCart instances. If one instance appends an item, all other carts see it. The correct approach is to use None as the default and create a new list inside the method.
class ShoppingCart:
def __init__(self, items=None):
self.items = items if items is not None else []This ensures each object gets its own list. The same rule applies to dictionaries, sets, and any other mutable object used as a default value.
Instance Variables and Inheritance
When a class inherits from a parent, instance variables defined in the parent's __init__ are still available in the child, but you must call the parent's initializer explicitly if you override __init__.
class Vehicle:
def __init__(self, wheels):
self.wheels = wheels
class Motorcycle(Vehicle):
def __init__(self, wheels, has_sidecar):
super().__init__(wheels)
self.has_sidecar = has_sidecarIf you forget to call super().__init__(), the child object will not have the wheels attribute. This is a common source of AttributeError in class hierarchies. Also, be aware that instance variables are not inherited in the sense of being copied; they are created by the initializer chain.
Memory and Performance Considerations
Instance variables are stored in a per-object dictionary (__dict__) by default. This allows dynamic attribute assignment but adds memory overhead compared to a fixed layout. For classes with many instances and a known set of attributes, you can use __slots__ to avoid the dictionary and reduce memory usage.
class Point:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = yNote: __slots__ prevents adding new attributes not listed, which can be a tradeoff. It also avoids a per-instance dictionary, which can reduce memory and may improve attribute access performance depending on the workload. Use it only when you are certain the attribute set is fixed and you need to optimize memory for many objects.
Managing Instance Variables Cleanly
For maintainability, keep instance variable names consistent and initialize them in one place. Use properties when you need validation or computed behavior. For example, you can define a property that enforces a non-negative value.
class Account:
def __init__(self, balance):
self._balance = balance
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("Balance cannot be negative")
self._balance = valueThis keeps _balance internal by convention and provides controlled access. It also centralizes validation logic, making the class easier to reason about. When you need to add behavior later, you can change the property implementation without breaking callers.
Instance variables are a fundamental part of Python's object model. Knowing how to declare them, how they behave with inheritance, and how to avoid common pitfalls like mutable defaults will help you write robust, maintainable code.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.