Adam Lombard
Posted on November 20, 2020
In Python, a method provides functionality to a Class.
There are, broadly, three types of methods:
- Class Methods : Provide functionality to a class itself
- Instance Methods : Provide functionality to one instance of a class
- Static Methods : Provide functionality that can be accessed from a class or from one instance of a class
Consider the following Python class, which defines a Person
object and the methods which allow that object to say "hello":
class Person():
# (Discussing __init__ is beyond the scope of this
# tutorial)
def __init__(self, first_name):
self.first_name = first_name
# Instance methods are the default method type in a
# class definition. They receive the class instance
# itself as their first argument. By convention,
# the parameter for this argument is labeled 'self'.
def say_hi_from_an_instance(self):
print(f"Hello! My name is {self.first_name}.")
# Class methods are defined using a special
# decorator, and receive the class as the first
# argument. By convention, the parameter for this
# argument is labeled 'cls'.
@classmethod
def say_hi_from_the_class(cls):
print(f"Hello! I am a {cls.__name__}.")
# Static methods are defined using a special
# decorator. They are available on the class and on
# instances of the class.
@staticmethod
def say_hi_from_anywhere():
print("Why, hello!!!")
Now, from the class:
# We can call the class method greeting
> Person.say_hi_from_the_class()
Hello! I am a Person.
# But we cannot call the instance method greeting
> Person.say_hi_from_an_instance()
Traceback ...
TypeError: say_hi_from_an_instance() missing 1 required positional argument: 'self'
While, from an instance of the class:
> a_person = Person('Louise')
# We can call the instance method greeting
> a_person.say_hi_from_an_instance()
Hello! My name is Louise.
# And we can still call the class method greeting
> a_person.say_hi_from_the_class()
Hello! I am a Person.
Static methods are available on both classes and class instances. They are intended to provide functionality that does not rely on the class or instance itself:
> Person.say_hi_from_anywhere()
Why, hello!!!
> a_person.say_hi_from_anywhere()
Why, hello!!!
See also: Ruby: class methods vs. instance methods
Was this helpful? Did I save you some time?
🫖 Buy Me A Tea! ☕️
💖 💪 🙅 🚩
Adam Lombard
Posted on November 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.