Hello, Explorer! Today, we're delving into the realm of Python's Object-Oriented Programming (OOP), focusing on class attributes and methods. Our goal is to grasp these concepts using clear, practical examples. Let's get started!
Class attributes are properties of class instances. For instance, a Spaceship
class could include attributes such as color, max speed, and fuel capacity. These are defined within the class block, as shown below:
These attributes can be accessed through a class instance, like so:
Class methods define a class's behavior. For example, a spaceship can fly. Methods are essentially functions within a class. The fly
method below enables an instance of the Spaceship
class to fly:
Note, that when referring to class attributes inside the class, you should always use the self
keyword that's always provided as a first parameter in every method of the class, similarly to how we used , and in the example above. At the same time, the provided parameter is just used as is, as it's not a class attribute but an external parameter.
