Introduction to Object-Oriented Python
Model real things with classes and objects
Dog is the blueprint, then Rex and Bella are two dog objects made from it. Each object carries its own information and can do its own actions.
- explain what a class and an object are,
- write a class with
__init__, attributes, and methods, - create objects and use their attributes and methods.
1. Classes and objects: the blueprint idea
Think about a cookie cutter. The cutter is not a cookie — it is the shape that decides how each cookie will look. You can use one cutter to make many cookies. Each cookie is real and separate, but they all follow the same shape.
In Python, a class is like the cookie cutter (the blueprint), and an object is like one real cookie made from it. We say an object is an instance of the class.
2. Writing your first class
We create a class with the word class, a name that starts with a capital letter, and a colon. Everything inside is indented. Here is a simple Dog class:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
A few new words to notice:
class Dog:starts the blueprint. Class names usually start with a Capital letter.def __init__(self, ...)is a special setup method. It runs automatically every time we make a new object.selfmeans this particular object. It lets each object keep its own data.