Python 3D Academyবাংলা

Classes and objects

🌍 In real life. Your school has one design for a student ID card. It says every card has a name, a class and a roll number. The design itself isn't anybody's card. The office uses it to print a card for each student, and every card has the same boxes, filled in differently.

Python works the same way:

  • the design is a class
  • each card printed from it is an object (also called an instance)
  • the boxes on a card are its attributes

The idea in one sentence: a class is a blueprint, and each object made from it carries its own values in attributes.

Its words:

  • class: the blueprint, class Dog:
  • object (or instance): one thing made from the blueprint, Dog("Rex", 3)
  • attribute: a value stored on an object, read with a dot: rex.name
  • __init__: the method Python runs to set up each new object; self is that new object

Step by step, for rex = Dog("Rex", 3):

  1. Python makes a new, empty Dog object.
  2. It runs __init__ with self = that object, name = "Rex", age = 3.
  3. self.name = name writes "Rex" onto the object, and self.age = age writes 3.
  4. The finished object is handed back and stored in rex.

Why bother? Without classes, a program about pets might keep one list of names and another list of ages. Then names[2] and ages[2] are only supposed to belong to the same pet. Sort or remove from one list and forget the other, and the data silently goes wrong. A class keeps each pet's data together, in one object.

Here is the blueprint for a dog, then two real dogs made from it. Watch the machine:

  • class Dog: starts the blueprint
  • __init__ is the special method Python runs every time you make a new object
  • self is the brand-new object, so self.name = name writes the name onto that object
  • Dog("Rex", 3) calls the class like a function and gives back the new object
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

rex = Dog("Rex", 3)
fido = Dog("Fido", 5)
print(rex.name, rex.age)
print(fido.name, fido.age)
One blueprint, two dogs. Each dog keeps its own name and age.

You read an attribute with a dot, rex.age, and change it the same way. Changing one object leaves the others alone, just as writing on Rex's card doesn't change Fido's. By tradition, class names start with a capital letter (Dog, Student), so you can tell them from ordinary variables.

class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll

ana = Student("Ana", 7)
bo = Student("Bo", 12)
ana.roll = 8
print(ana.name, ana.roll)
print(bo.name, bo.roll)
print(type(ana).__name__)
type(...).__name__ tells you which class an object was made from.

Mistakes and edge cases.

  • Forgetting an argument. Dog() for def __init__(self, name): gives TypeError: Dog.__init__() missing 1 required positional argument: 'name'.
  • Forgetting self. name = name inside __init__ only makes a local variable; then d.name gives AttributeError: 'Dog' object has no attribute 'name'.
  • A misspelt init. With def __init(self, name): (one underscore missing at the end), Python never runs it: Dog("Rex") gives TypeError: Dog() takes no arguments.
  • Expecting objects to share values. Each object has its own attributes; changing ana.roll leaves bo.roll alone.

Quiz

  1. What does this print?

    class Cat:
        def __init__(self, name):
            self.name = name
    
    c = Cat("Tom")
    print(c.name)
  2. What does this print?

    class Box:
        def __init__(self, size):
            self.size = size
    
    a = Box(2)
    b = Box(7)
    a.size = 10
    print(a.size, b.size)
  3. In __init__(self, name), what is self?

    • The new object being made
    • The class itself
    • The first value you pass in the brackets
  4. What does this print?

    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y
            self.total = x + y
    
    p = Point(3, 4)
    print(p.total)
  5. Which line has a mistake?

    class Dog:
        def __init__(self, name):
            name = name
    
    rex = Dog("Rex")
    print(rex.name)

Coding tasks

  1. Write a class Book whose __init__ takes a title and an author and stores both as attributes.

  2. Write a class Rectangle that stores width and height, and also an attribute area worked out in __init__.

  3. Write a class Counter with no parameters (besides self) that starts every new object with count 0.