method-types-blog.png

Types of Methods In Python

Last Updated | Jan, 13, 2021 By Kingsley Ijomah
There are three types of methods in Python: instance methods, static methods and class methods. Once you get to the level of learning OOP, knowing the differences between these methods can make a lot of difference, in this post we are going to explore their differences.
method-types-pinterest2.png

Methods Vs Functions in Python

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.

code
# 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.

Instance Methods in Python

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:

code
# 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 in Python

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.

code
# 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.

Class Methods in Python

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.

code
# 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

code
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.

code
'''
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

Final Thoughts

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:

  1. Instance Methods: The most common method type. you can access data and properties unique to each instance.
    1. access class variables
    2. access instance variables
    3. call other instance methods
    4. call static methods
    5. call class methods
  2. Static Methods: Does not have the self keyword and cannot access data in the class, it is self-contained.
    1. no direct access to class variables
    2. no direct access to instance variables
    3. no access to instance methods
    4. no direct access to class method ( possible with Class.method_name )
  3. Class Methods: Similar to the static method but has cls keyword and access to class data but not instance data
    1. access class variables
    2. access static method
    3. no access to instance variables
    4. no access to instance methods

MY STORY

My name is Kingsley Ijomah, I am the founder of CODEHANCE, an online education platform built with you in mind, a place where I express my gratitude to a skill ( coding ) which has changed my life completely.

Learn To Code With Me.
FREE course included.

GET IN TOUCH

Enter your email address:

Delivered by FeedBurner