Tutorial
Class Methods In Python
In Python, a method is a function that belongs to a class. Methods let objects do things, like print information or perform actions.
Methods usually take self as the first input. This allows them to access data stored in the object.
Creating a Method
Let’s add a method to our Car class that shows the car’s details.
Methods with Parameters
Methods can also take extra inputs. For example, we can add a method to update the color of the car.
Returning Values from Methods
Methods can also return values. Here’s an example that returns a string with the car details instead of printing them.
Why Use Methods?
Methods help organize your code. Instead of writing separate print statements every time, you can just call a method that does it for you.
What You Learned
- A method is a function that belongs to a class.
- Methods use
selfto access data inside an object. - Methods can take extra inputs to perform actions on an object.
- Methods can also return values for later use.
- You can call a method using dot notation, like
my_car.show_info().