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
classkeyword. - 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 self. 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 self in more examples in the next lessons.
In Python, proper indentation is crucial, especially in the body of a class. Python relies on indentation to determine where methods begin and end. So, ensure that your code is neat with proper indentation.
In our Star class:
classdenotes the class definition.Staris our class name.def twinkle(self):creates a method namedtwinkle.print("Twinkle, twinkle, little star...")prints a phrase when thetwinklemethod is invoked.
Once we have defined our Star class, we can use it to create individual instances, or in other words, individual stars!
An instance is a specific object created from a particular class. You can create an instance from the Star class like this:
Here, my_star is an instance of the Star class. Notice the parentheses after Star - we use them to call the class as if it were a function.
