Create your methods
A class has a set of associated functions that allow you to work with it. These functions are known as methods, and there are the following types:
- β¨ Magic: Also known as dunder methods. They are methods defined by Python with special behaviors.
- π§ Instance: These are the βnormalβ and most common methods defined above. They are intended to access or modify some of the attributes of the object or instance. Therefore, they have access to it through
self
. - ποΈ Class: They can only access and modify the class attributes, not being able to modify specific objects since they have no knowledge of them. They access the class through
cls
. - π Static: They cannot access either object or class attributes. Therefore, they can only access parameters passed by input.
Below are examples of all these methods to help you choose the next time you need to define one.
β¨ Magic methods are those that begin and end with __
, such as __init__
. We will see them in more detail in the section on dunder or magic methods. For example, the constructor seen earlier is a magic method.
class Person:
def __init__(self, name):
self.name = name
π§ Instance methods are the most used and common ones. They access object information and allow us to change or query information about them. The self
refers to the object on which they are called. Every instance method has the self
.
class Person:
def __init__(self, age):
self.age = age
# Instance method
def is_adult(self):
return self.age >= 18
p = Person(20)
print(p.is_adult()) # True
ποΈ Class methods can only access the attributes of the class. They cannot access or modify the specific attributes of each object.
Next, we see a class Person
that has a class attribute counter
. This attribute is incremented each time a person is created. The class method total_people
returns the number of people that have been created, but does not have access to name
.
Notice that the class method uses cls
. That is, it has access to the class.
class Person:
counter = 0
def __init__(self, name):
self.name = name
Person.counter += 1
# Class method
@classmethod
def total_people(cls):
return cls.counter
p1 = Person("Ana")
p2 = Person("John")
print(Person.total_people()) # 2
π Static methods have access to neither class nor instance attributes. They are functions grouped under a class. They are usually useful when we want to group a set of related functions under the same namespace. As you can see, we do not create objects, since these methods are accessed directly from the class.
These static methods do not have access to either cls
or self
as seen above.
class Calculator:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def subtract(a, b):
return a - b
print(Calculator.add(10, 5)) # 15
print(Calculator.subtract(10, 5)) # 5