Classes and Objects
You will create classes, objects, attributes, methods, and useful string output.
Build your own object type
A class is a blueprint. An object is one thing made from that blueprint. Classes help you group related data and actions.
class ClassName:
def __init__(self, value):
self.value = value
def show(self):
print(self.value)
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f'My name is {self.name}.')
pet = Dog('Milo', 3)
print(pet.age)
pet.introduce()
__init__ runs when you create an object. self means the current object, so self.name and self.age belong to that dog.
Instance and class attributes
class Student:
school = 'PyQuest Academy'
def __init__(self, name):
self.name = name
def describe(self):
print(f'{self.name} studies at {self.school}.')
first = Student('Ava')
second = Student('Noah')
first.describe()
second.describe()
print(Student.school)
| Attribute type | Where it is stored | Example |
|---|---|---|
| Instance attribute | On one object | self.name |
| Class attribute | On the class, shared by objects | Student.school |
Each student has its own name instance attribute. Both students can use the shared school class attribute. A function inside a class is called a method.
Choose a readable string
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __str__(self):
return f'{self.title} ({self.pages} pages)'
book = Book('Python Basics', 120)
print(book)
Key points
- A class is a blueprint for objects.
- __init__ sets up a new object.
- self refers to the current object.
- Instance attributes belong to one object.
- __str__ makes printed objects readable.
Worked example
Model a student once, then stamp out as many as needed — data (name, marks) plus behaviour (grade) live together.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def grade(self):
return "A" if self.marks >= 80 else "B"
print(Student("Mim", 84).grade())
How it works, step by step
- __init__ runs automatically on creation, filling self.
- self.name / self.marks belong to THIS student.
- Methods read attributes through self — grade() checks this object's marks.
References & Further Reading
Related entries from PyLabs's own reference library.
- type() (Find out what type of value an object is.)
- property() (Create a managed attribute for a class.)
- getattr() (Read an attribute when its name is stored in a string.)
- setattr() (Set an attribute on an object using its name as text.)
Practice exercise
Not passed yetCreate a Circle class. Its __init__ method should save a radius. Add a show_radius method that prints Radius: 4 for a circle with radius 4.
# Write your code below
Check yourself
Classes and Objects quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.