13.2Constructors, Instance Variables and Class Variables
Covers IGNOU MCS-201 §13.2, 13.3
Calling a separate set_sides() method after creating each object is easy to forget. A constructor sets an object up automatically the moment it is created. This section also separates the two kinds of variables a class can have.
__init__ is called once for each new object, immediately after Python creates it.
Its first parameter is the new object (self); the remaining parameters receive the arguments passed to the class.
It returns nothing (None); it only fills in the object.
Default arguments make parameters optional: def __init__(self, st="Welcome to Python World"):.
Instance variables and class variables
Instance variable
Class variable
Defined
By assigning to self.name (usually in __init__, but in any method)
In the class body, outside all methods
Belongs to
One object
The class, shared by all its objects
Accessed as
obj.name (or self.name inside methods)
ClassName.name (also readable as obj.name)
Example
Each student’s name and marks
school = "IGNOU", a counter of students created
Writing obj.name = value for a name that is a class variable does not change the class variable; it creates a new instance variable on that object, which hides the class variable for that object only. To change the shared value, assign through the class: ClassName.name = value.
Printing objects: str
Printing an object normally shows something like <__main__.Student object at 0x7f…>. Defining __str__(self) to return a string controls what print() and str() show.
Key takeaways
__init__ initialises each new object automatically.
self is the object itself, not its class.
Instance variables are set on self; class variables are set in the class body and shared.
__str__ defines how an object is printed.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a class BankAccount whose constructor takes the owner’s name and an opening balance (default 0), with methods deposit(amount) and withdraw(amount) that refuses to go below zero, and a __str__ that shows the owner and balance.
Show worked answer
class BankAccount: with def __init__(self, owner, balance=0): self.owner = owner; self.balance = balance, def deposit(self, amount): self.balance += amount, def withdraw(self, amount): that does if amount > self.balance: print("Insufficient balance"), else: self.balance -= amount, and def __str__(self): return f"{self.owner}: {self.balance}". Then acc = BankAccount("Nav", 1000); acc.deposit(500); acc.withdraw(2000); print(acc) prints “Insufficient balance” and then Nav: 1500.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/classes-in-python/constructors-instance-variables-and-class-variables/ to read this page.