Topics covered in this post:
If you are new to Python you might come across methods and functions and not know what the differences are. In programming language such Java which is also an object-oriented programming (OOP) language, there is no concept of functions in it as in Python.
Let's quickly clear these differences before we get into types of methods in Python.
Method
A method is similar to a function except it is associated with class/object, it is called on an object.
Function
A function is a block of code to carry out a specific function, it is not associated with a class/object, it is called by name.
# Example Python method
class Pet:
def my_method(self):
print("I am a Dog")
# create object saved in `dog`
dog = Pet()
# call method on object
dog.my_method() #output: I am a Dog
# Example Python function
def sum(a, b):
print(a + b)
# call function by name
sum(10, 30) #output: 40
Well done! now you know the difference between a method and a function.
The most common type of method in Python classes are the Instance methods, they make it possible for us to reuse methods by passing in different properties to them.
When instance methods are created, the first method parameter is reserved and usually called self
, although that could be changed to any valid parameter name. The self
parameter name has access to instance variables (parameters of the class) as well as the class's instance methods.
You can also use the Python function isinstance(object, Class)
to check if an object was instantiated ( a process of creating an instance ) from a given class.
Let's have a look at an example:
# Instance Method Example in Python
class Student:
"""Calculates student average"""
def __init__(self, a, b):
self.a = a
self.b = b
def avg(self):
return (self.a + self.b) / 2
'''
create two instances of Student class (tim and sally)
pass in different arguments to the objects
each object is saved as instance variables self.a, self.b
'''
tim = Student(10, 20)
sally = Student(15, 25)
'''
each object calls the avg() method, but the instance
variables are different in each call
'''
print(tim.avg()) #output: 15.0
print(sally.avg()) #output: 20.0
'''
Use Python's function to check if tim and sally are indeed
instances of the class Student
'''
print(isinstance(tim, Student)) # True
print(isinstance(sally, Student)) # True
Static methods are methods used in a class in some way, but don't have access to any class specific properties ( data ). They don't require the self
parameter like the instance methods do.
Static methods can also be called without the need to first create an instance ( object ) of the class.
# Static Method Example in Python
class Student:
"""Calculates student average"""
def __init__(self, a, b):
self.a = a
self.b = b
def avg(self):
return (self.a + self.b) / 2
@staticmethod
def notice():
return "Exams next week!"
# static method called directly on class
print( Student.notice() ) # output: Exams next week!
# create object and call static method on it
sally = Student(10, 15)
print( sally.notice() ) # output: Exams next week!
The @staticmethod decorator was used to tell Python that this method is a static method.
Static methods are great for utility methods used to perform tasks in isolation, they cannot access class data and should be completely self contained.
A class method cannot access instance data since they don't have access to self
, but it does have access to another keyword cls
short for class, although this is a convention you can name it anything, it has to be the first parameter to your class method.
Just like static method, you don't need an instance ( object ) first, you can call class methods directly too.
# Class Method Example in Python
class Student:
"""Return info"""
name = "Kings College"
@classmethod
def info(cls):
return cls.name
print(Student.info()) # output: Kings College
jill = Student()
print(jill.info()) # output: Kings College
The @classmethod decorator was used to tell Python that this method is a class method.
Also we define the method with the cls
keyword, this gives us access to the class property name
class Student:
"""Return info"""
name = "Kings College"
def __init__(self, a, b):
self.a = a
self.b = b
@classmethod
def info(cls):
return cls.a
# AttributeError: type object 'Student' has no attribute 'a'
print(Student.info())
Above example demonstrate that you can't access instance variables from a class method, it will produce AttributeError
message.
But it is possible to access static methods from within a class method, remember static methods don't have self
or cls
parameter requirement, so makes it easy to call.
'''
It is possible to call a static method from a class method
'''
class Student:
name = "Kings College"
@classmethod
def info(cls):
return cls.static_method()
@staticmethod
def static_method():
return "static method called!"
print(Student.info()) #ouput: static method called!
'''
It is possible to call a static method from an instance method
'''
class Student:
name = "Kings College"
def instance_method(self):
return self.static_method()
@staticmethod
def static_method():
return "static method called!"
jill = Student()
print(jill.instance_method()) # output: static method called!
'''
It is possible to call a class method from an instance method
'''
class Student:
name = "Kings College"
def instance_method(self):
return self.class_method()
@classmethod
def class_method(cls):
return cls.name
jill = Student()
print(jill.instance_method()) # output: Kings College
Phew! we have come to the end of this post, you have learnt about the three different types of methods in Python with examples, so in summary:
self
keyword and cannot access data in the class, it is self-contained.cls
keyword and access to class data but not instance data