0% found this document useful (0 votes)
1 views10 pages

Opps

The document explains the concepts of instance variables, class variables, and static methods in Python, highlighting their definitions, access methods, and use cases. It also details various magic methods, such as __init__, __str__, __add__, and others, describing their purposes and how they can be implemented in classes. Additionally, a comparison summary table is provided to differentiate between instance variables, class variables, and static methods.

Uploaded by

Nitin Ojha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views10 pages

Opps

The document explains the concepts of instance variables, class variables, and static methods in Python, highlighting their definitions, access methods, and use cases. It also details various magic methods, such as __init__, __str__, __add__, and others, describing their purposes and how they can be implemented in classes. Additionally, a comparison summary table is provided to differentiate between instance variables, class variables, and static methods.

Uploaded by

Nitin Ojha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

🔹 1.

Instance Variable
✅ What it is:
A variable that is unique to each object (instance) of a class.

✅ Accessed using: self.<variable_name>


✅ Defined inside: __init__() or any instance method
✅ Use case: To store object-specific data.
🔧 Example:
class Student:
​ student_name=”chirag”
def __init__(self, name, age):
self.name = name # instance variable
self.age = age # instance variable

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.

✅ Accessed using: ClassName.var or self.var


✅ Defined directly in the class body (outside methods)
✅ Use case: To store data common to all instances.
🔧 Example:
class Student:
school_name = "Greenwood High" # class variable

def __init__(self, name):


self.name = name # instance variable

s1 = Student("Alice")
s2 = Student("Bob")

print(s1.school_name) # Greenwood High


print(s2.school_name) # Greenwood High

Student.school_name = "Hilltop School"

print(s1.school_name) # Hilltop School


🔹 3. Static Variable (aka Static Method Context)
There is no special "static variable" keyword, but when used in the context of:

🔸 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.

✅ Defined using: @staticmethod decorator


✅ Use case: Utility/helper methods
🔧 Example:
class Calculator:
@staticmethod
def add(a, b):
return a + b

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

Defined In __init__ or Class body Not applicable


methods

Accessed By self.var Class.var or No access


self.var

Unique per Object? ✅ Yes ❌ Shared Not used

Can Static Method ❌ No ❌ No ❌ No


Access It?

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.

🔹 __init__(self, ...) → Constructor


●​ Called automatically when an object is created.​

●​ Initializes instance variables.​

class Person:
def __init__(self, name):
self.name = name

p = Person("Nancy") # __init__ is called here

🔹 __str__(self) → Printable string


●​ Called when you use print() on an object.​

●​ Returns a human-readable string.​

class Person:
def __str__(self):
return f"Person name: {self.name}"

🔹 __repr__(self) → Official string


●​ Called when you do repr(obj) or just type the object in the shell.​

●​ Should return an unambiguous string (useful for debugging).​

def __repr__(self):
return f"Person('{self.name}')"

🔹 __add__(self, other) → + operator


def __add__(self, other):
return self.value + other.value

🔹 __sub__, __mul__, __truediv__, __floordiv__, __mod__, __pow__


These correspond to:

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__ >=

def __eq__(self, other):


return self.num * other.den == self.den * other.num # Compare
fractions

🔹 __len__(self) → len(obj)
Returns the length of the object.

def __len__(self):
return len(self.items)

🔹 __getitem__, __setitem__, __delitem__


Used to support indexing and slicing:
def __getitem__(self, index):
return self.data[index]

🔹 __call__(self, ...)
Makes an object behave like a function.

def __call__(self, x):


return x * x

sqr = Math()
print(sqr(5)) # calls __call__

🔹 __iter__ and __next__


Used to make objects iterable (e.g., in for loops).

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 __add__(self, other):


return Number(self.value + other.value)

def __eq__(self, other):


return self.value == other.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

__str__ String representation

__repr__ Official string (debugging)

__add__, etc. Arithmetic operators

__eq__, etc. Comparison operators

__len__ Length of object


__getitem__ Indexing like obj[i]

__call__ Callable object

__iter__, Iterable support


__next__

You might also like