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;selfis that new object
Step by step, for rex = Dog("Rex", 3):
- Python makes a new, empty Dog object.
- It runs
__init__withself= that object,name= "Rex",age= 3. self.name = namewrites "Rex" onto the object, andself.age = agewrites 3.- 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 objectselfis the brand-new object, soself.name = namewrites the name onto that objectDog("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)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__)Mistakes and edge cases.
- Forgetting an argument.
Dog()fordef __init__(self, name):givesTypeError: Dog.__init__() missing 1 required positional argument: 'name'. - Forgetting self.
name = nameinside__init__only makes a local variable; thend.namegivesAttributeError: '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")givesTypeError: Dog() takes no arguments. - Expecting objects to share values. Each object has its own attributes; changing
ana.rollleavesbo.rollalone.
Quiz
What does this print?
class Cat: def __init__(self, name): self.name = name c = Cat("Tom") print(c.name)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)In
__init__(self, name), what isself?- The new object being made
- The class itself
- The first value you pass in the brackets
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)Which line has a mistake?
class Dog: def __init__(self, name): name = name rex = Dog("Rex") print(rex.name)
Coding tasks
Write a class
Bookwhose__init__takes atitleand anauthorand stores both as attributes.Write a class
Rectanglethat storeswidthandheight, and also an attributeareaworked out in__init__.Write a class
Counterwith no parameters (besides self) that starts every new object withcount0.