Similar to how you can think of attributes as instance variables, you can think of Python methods as instance functions. The __init__() constructor that you defined in the previous lesson is one of these methods.
Info: Dunder init and other dunder methods that you'll get to know in the next lesson are sometimes called special methods or magic methods. There's nothing special or magical about them, as you'll see in this lesson. The only difference to a "normal" method is that they aren't meant to be called explicitly.
How to Write Class Methods
You can write your own Python methods for your class objects, and these methods will give your objects functionality.
Class Method Example
In the code snippet below, you'll add an expire() method to your Ingredient() class:
class Ingredient:
"""Models a food item used as an ingredient."""
def __init__(self, name):
self.name = name
def expire(self):
"""Expires the ingredient."""
print(f"whoops, these {self.name} went bad...")
self.name = "expired " + self.name
First, you defined your method called expire(). This method prints a short message and adds the string "expired " in front of the instance's name. You can instantiate a new Ingredient() with any name you want to. But once you call the .expire() method on it once, the name of your ingredient will have forever changed to "expired name":
i = Ingredient("peas")
print(i.name) # OUTPUT: peas
i.expire()
print(i.name) # OUTPUT: expired peas
print(i.name) # OUTPUT: expired peas
In real life, once your ingredient has expired, there's no way to get it un-expired again.
Info: In your Ingredient() class you would be able to change the .name attribute of your instance also after calling .expire(). It is, after all, just a variable name, and you can re-assign it to any value you want. However, when you write a program based on your class code, you'd want to define clear and specific ways how the name value can be changed.
The reason why your Ingredient() instance has access to change its .name attribute from within .expire() is because of the self argument that you've been passing as the first parameter into each of your methods. It's time to find out more about it in the next lesson.
Summary: Python Methods
- Python classes can contain Python methods
- Class methods are available to all instances of the class
- Class methods are defined inside the class and follow the stand method syntax