PYTHON — Types Of Python Methods A Recap And Review
I’m not a great programmer; I’m just a good programmer with great habits. — Kent Beck
Insights in this article were refined using prompt engineering methods.
PYTHON — Staying On The Screen In Python
Python Method Types Recap & Review
In Python, there are different types of methods such as regular methods, class methods, and static methods.
- Regular methods: These methods require an object instance to be called on. They are the most common type of method in Python classes.
- Class methods: These methods need a class and have access to the class. They are identified with the
@classmethod
decorator. - Static methods: These methods don’t have access to the object instance or the class at all. They are used to namespace functions and are identified with the
@staticmethod
decorator.
Here is an example of these method types in action:
class Pizza:
def __init__(self, ingredients):
self.ingredients = ingredients
def __str__(self):
return f"A {', '.join(self.ingredients)} pizza"
@classmethod
def margherita(cls):
return cls(["mozzarella", "tomatoes"])
@staticmethod
def make_static():
return "This is a static method"
pizza1 = Pizza(["cheese", "tomatoes"])
print(pizza1) # Output: A cheese, tomatoes pizza
pizza2 = Pizza.margherita()
print(pizza2) # Output: A mozzarella, tomatoes pizza
print(Pizza.make_static()) # Output: This is a static method
In the above example, __init__
is a regular method, margherita
is a class method, and make_static
is a static method.
It is essential to understand the differences between these method types and when to use them in practical scenarios, such as building APIs in an object-oriented fashion.
For further exploration and learning, consider considering the Object-Oriented Programming (OOP) With Python Learning Path.
In summary, regular methods are called on object instances, class methods are called on the class and can modify it, and static methods are called on the class but don’t have access to it. Understanding these method types is crucial for effective object-oriented programming in Python.