Opps
Opps
Instance Variable
✅ What it is:
A variable that is unique to each object (instance) of a class.
s1 = Student("Alice", 20)
s2 = Student("Bob", 22)
print(s1.name) # Alice
print(s2.name) # Bob
🔹 2. Class Variable
✅ What it is:
A variable that is shared among all objects of a class.
s1 = Student("Alice")
s2 = Student("Bob")
🔸 Static Method
✅ What it is:
A method that does not access either self or cls, meaning it has no access to instance or
class variables.
print(Calculator.add(5, 3)) # 8
This add() method doesn’t care about any instance or class—it just performs addition.
🔍 Comparison Summary Table
Feature Instance Class Variable Static Method Variable
Variable Access
Use Case Store object data Store shared data Logic that doesn’t use
object/class data
✅ Most Common __magic__ Methods Explained
Below is a detailed explanation of important magic methods, how they work, and what they’re
used for.
class Person:
def __init__(self, name):
self.name = name
class Person:
def __str__(self):
return f"Person name: {self.name}"
def __repr__(self):
return f"Person('{self.name}')"
Method Operator
__sub__ -
__mul__ *
__truediv_ /
_
__floordiv //
__
__mod__ %
__pow__ **
You can define them in your class to customize how these operators work.
🔹 __eq__, __lt__, __gt__, __le__, __ge__, __ne__
These are used for comparisons:
Method Compariso
n
__eq__ ==
__ne__ !=
__lt__ <
__le__ <=
__gt__ >
__ge__ >=
🔹 __len__(self) → len(obj)
Returns the length of the object.
def __len__(self):
return len(self.items)
🔹 __call__(self, ...)
Makes an object behave like a function.
sqr = Math()
print(sqr(5)) # calls __call__
def __iter__(self):
self.index = 0
return self
def __next__(self):
if self.index < len(self.data):
result = self.data[self.index]
self.index += 1
return result
else:
raise StopIteration
🔁 Example Using Multiple Magic Methods
class Number:
def __init__(self, value):
self.value = value
def __str__(self):
return f"Value: {self.value}"
a = Number(10)
b = Number(20)
c = a + b
print(c) # Value: 30
print(a == b) # False
✅ Summary Table
Magic Method Purpose
__init__ Constructor