MCS-201 · Unit 13

Classes in Python

Section 1 of 7

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

13.1Object-Oriented Programming: Classes and Objects

Covers IGNOU MCS-201 §13.0, 13.2

In C you used a structure to group data (Unit 6) and separate functions to work on it. A class goes one step further: it bundles the data and the functions that operate on it into one unit. Objects created from the class carry their own data and know how to work with it.

The object-oriented idea

Four ideas appear throughout OOP:

IdeaMeaningIn Python
EncapsulationKeep data and the methods that use it together; let users work through methods without knowing the detailsA class with attributes and methods
InheritanceBuild a new class from an existing one, reusing its codeclass Child(Parent):
PolymorphismOne interface, many forms: different objects respond to the same call in their own wayOverriding, operator overloading, duck typing
AbstractionShow only what a user needs; hide the restPublic methods; names starting with _ mark internal details

Classes and objects

Defining a class

Syntax
class ClassName:
    """Optional docstring."""
    class_variable = value          # shared by all objects

    def method_name(self, parameters):
        statements
  • class is the keyword; by convention class names use CapitalisedWords.
  • The header ends with a colon and the body is indented, exactly like def and if.
  • A method is a function defined inside a class. Its first parameter, conventionally named self, receives the object the method is called on.
  • Calling a class like a function, Rectangle(), creates a new object.
  • obj.method(args) calls a method; Python turns it into ClassName.method(obj, args), which is how self gets its value.

Namespaces

A class has its own namespace holding its methods and class variables, and each object has a separate namespace holding its own attribute values. This is why two rectangles can have different heights while sharing one copy of the methods.

Namespaces of the Rectangle class and two objects
        class Rectangle: set_sides, area, perimeter
               /                         \
  object r1: height=4, width=5     object r2: height=2, width=6

In Python, everything is an object: 28, "IGNOU" and [1, 2] are objects of the classes int, str and list. Every object has an identity (id()), a type (type()) and a value.

Key takeaways

  • OOP groups data and behaviour into objects created from classes.
  • class Name: defines a class; methods are functions in it with self first.
  • Calling the class (Name()) creates an object; obj.method() calls a method on it.
  • Each object has its own namespace of attribute values.

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

What is a class?

Show answer

Answer: B. A blueprint that defines the attributes and methods of its objects

Objects (instances) are created from the class; the class describes what they contain and can do.

Question 2 · multiple choice

What does self refer to inside a method?

Show answer

Answer: C. The object on which the method was called

r1.area() passes r1 as self.

Question 3 · multiple choice

What does this program print?

Python · quiz_counter.py
class Counter:
    def start(self):
        self.value = 0
    def tick(self):
        self.value += 1
        return self.value

a = Counter()
b = Counter()
a.start()
b.start()
a.tick()
print(a.tick(), b.tick())
Show answer

Answer: C. 2 1

Each object has its own value; a is ticked twice (2) and b once (1).

Question 4 · multiple choice

Which is the correct way to create an object of class Car?

Show answer

Answer: B. my_car = Car()

Calling the class creates an instance. Python has no new keyword, and Car without parentheses is the class itself.

Question 5 · multiple choice

What is the perimeter returned by a correct Rectangle method for height 3 and width 7?

Show answer

Answer: D. 20

Perimeter = 2 × (3 + 7) = 20; 21 is the area and 42 is the wrong formula 2 × (3 × 7).

Question 6 · short answer

Write a class Circle with methods set_radius(r), perimeter() and area() (Check Your Progress 1, Q1), and show how to use it for radius 2.

Show worked answer

import math, then class Circle: with def set_radius(self, r): self.r = r, def perimeter(self): return 2 * math.pi * self.r and def area(self): return math.pi * self.r ** 2. Use: c = Circle(), c.set_radius(2), print(round(c.perimeter(), 2), round(c.area(), 2)), which prints 12.57 12.57. Every method reads the same attribute self.r set by set_radius.

↑ ↓ move↵ openTab switch type