Today, we delve into a key concept in Object-Oriented Programming (OOP) - classes. Our aim is to understand what classes are, how to create our own Python classes, and how to use them.
Imagine the universe of OOP, where everything is an object. What about classes? They're the blueprints for creating these objects. Just like a blueprint for a house specifies everything about the house, such as the number of rooms, the size of each room, and whether it has a backyard or not, a class in Python defines what an object will be like, too!
Creating a class involves:
- Using the
class
keyword. - Writing the class name, which should start with a capital letter.
- Correctly indenting the body of the class.
Let's create our first class, Star
:
The Star
class has a twinkle
method that prints a phrase.
Did you note the twinkle
method has a self
parameter? In Python, self
represents the instance of the class itself. It's used as the first parameter in function definitions inside the class, and if you want to call a function within the class (or refer to any data in the class), you need to use . It's kind of like saying "me" or "myself" when you're referring to yourself in a conversation, but in this case, the conversation is all the actions happening inside the class. We will cover in more examples in the next lessons.
