MCS-201 · Unit 13

Classes in Python

Section 2 of 7

Block 4 · Unit 13Classes in Python10 min · Section 2 of 7

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.

The constructor init

Constructor syntax
class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

s = Student("Asha", 82)      # __init__(s, "Asha", 82) runs automatically
  • __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 variableClass variable
DefinedBy assigning to self.name (usually in __init__, but in any method)In the class body, outside all methods
Belongs toOne objectThe class, shared by all its objects
Accessed asobj.name (or self.name inside methods)ClassName.name (also readable as obj.name)
ExampleEach student’s name and marksschool = "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 1 · multiple choice

When does __init__ run?

Show answer

Answer: B. Automatically each time a new object of the class is created

Student("Asha", 82) creates the object and immediately calls __init__ on it with the arguments.

Question 2 · multiple choice

Where is a class variable defined?

Show answer

Answer: C. In the class body, outside all methods

Names assigned directly in the class body belong to the class and are shared by all instances.

Question 3 · multiple choice

What does this program print?

Python · quiz_classvar.py
class Shop:
    tax = 18
    def __init__(self, price):
        self.price = price

a = Shop(100)
b = Shop(200)
a.tax = 5
print(a.tax, b.tax, Shop.tax)
Show answer

Answer: C. 5 18 18

a.tax = 5 creates an instance variable on a only; b and the class still see the class variable 18.

Question 4 · multiple choice

What does this program print?

Python · quiz_init.py
class Code1:
    def __init__(self, st="Welcome to Python World"):
        self.st = st
    def output(self):
        print(self.st)

Code1().output()
Code1("Hi").output()
Show answer

Answer: A. Welcome to Python World, then Hi

Default arguments work in constructors exactly as in functions; the second call overrides the default.

Question 5 · multiple choice

What does print(obj) show for an object whose class defines no __str__ (or __repr__)?

Show answer

Answer: D. Something like <__main__.ClassName object at 0x…>

The default representation shows the class name and the object’s memory address; define __str__ for a readable form.

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.

↑ ↓ move↵ openTab switch type