Instance Variables

Object-specific data

Interview Relevant: Basic OOP

Instance Variables

Data unique to each object.

Code Examples

Instance variables for object state.

python
1class Counter:
2    def __init__(self):
3        self.count = 0  # Instance variable
4
5    def increment(self):
6        self.count += 1
7
8# Each object has its own count
9c1 = Counter()
10c2 = Counter()
11c1.increment()
12c1.increment()
13print(c1.count)  # 2
14print(c2.count)  # 0 (independent)
15
16# Add attributes dynamically
17c1.name = "Counter 1"  # OK in Python!
18
19# Prevent dynamic attributes with __slots__
20class Strict:
21    __slots__ = ['x', 'y']
22    def __init__(self, x, y):
23        self.x = x
24        self.y = y
25
26s = Strict(1, 2)
27# s.z = 3  # AttributeError!

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In