What is a Class?
A class is a blueprint for creating objects. An object (also called an instance) is a specific thing built from that blueprint. Classes let you bundle data and the actions that work on it into one tidy unit. You define a class with the class keyword.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name, 'says woof')
The __init__ Method and self
The special method named __init__ is the constructor. Python runs it automatically when you create a new object, and it sets up the starting data. The first parameter, self, refers to the particular object being worked on. You use self to store and read the object attributes.
Creating and Using Objects
To make an object, call the class name like a function. Then use dot notation to reach attributes and methods.
d = Dog('Rex')
print(d.name) # Rex
d.bark() # Rex says woof
Here d is one instance of Dog. You could create many dogs, each with its own name.
Attributes and Methods
- An attribute is a piece of data stored on the object, like d.name.
- A method is a function defined inside a class that acts on the object.
Inheritance
A class can inherit from another to reuse its features. You write the parent class in round brackets after the child name. The child gets the parent methods and can add its own.
class Puppy(Dog):
def play(self):
print(self.name, 'is playing')
Because Puppy inherits from Dog, a puppy object can still bark as well as play. Inheritance saves you from repeating shared code and lets you model real relationships between things.
Why Use Classes?
Classes group related data and behaviour into one clear unit, which keeps large programs organised. Instead of many loose variables and functions, you get self-contained objects that each know their own data and how to act on it. This style, called object-oriented programming, is widely used for building games, apps, and simulations, because it mirrors how we naturally think about the world as a collection of interacting things.
Remember
- A class is a blueprint; an object is built from it.
- Define a class with the class keyword.
- __init__ is the constructor that runs when an object is created.
- self is the first parameter of methods and refers to the object.
- Write class Child(Parent) to inherit features.