Table of Contents

    Class Methods in Python: Understanding and Using Them Effectively

    You have read about function, higher order function, closures etc. Now, it is time to learn about their scope. Based on the scope, functions/methods are of two types. They are:

    • Class methods

    • Static methods

    Class Methods
    • A method defined inside a class is bound to its object, by default.

    • However, if the method is bound to a Class, then it is known as classmethod.

    • Consider the following two examples:

      • Example 1 defines the method getCirclesCount, bound to an object of Circle class.

      • Example 2 defines the classmethod getCirclesCount, bound to class Circle.

    Class Methods - Example

    Example 1

    class Circle(object):
        no_of_circles = 0
        def __init__(self, radius):
            self.__radius = radius
            Circle.no_of_circles += 1
        def getCirclesCount(self):
            return Circle.no_of_circles
    c1 = Circle(3.5)
    c2 = Circle(5.2)
    c3 = Circle(4.8)
    print(c1.getCirclesCount())     # -> 3
    print(c2.getCirclesCount())     # -> 3
    print(Circle.getCirclesCount(c3)) # -> 3
    print(Circle.getCirclesCount()) # -> TypeError
    Class Methods - Example

    Output of Example 1

    3
    
    3
    
    3
    
    TypeError: getCirclesCount() missing 1 required positional argument: 'self'
    • In Example 1, getCirclesCount method is bound to objects of Circle.

    • Hence when calling it,

      • on objects c1, and c2 resulted in 3.

      • on class Circle with object c3 as argument resulted in 3 again.

      • on class Circle without any object information resulted in TypeError.

    Class Methods - Example

    Example 2

    class Circle(object):
        no_of_circles = 0
        def __init__(self, radius):
            self.__radius = radius
            Circle.no_of_circles += 1
        @classmethod
        def getCirclesCount(self):
            return Circle.no_of_circles
    c1 = Circle(3.5)
    c2 = Circle(5.2)
    c3 = Circle(4.8)
    • In Example 2, getCirclesCount is decorated with classmethod.

    • Thus making it a class method, which bounds to class Circle.

    Class Methods - Example

    Example 2...

    print(c1.getCirclesCount())     # -> 3
    
    print(c2.getCirclesCount())     # -> 3
    
    print(Circle.getCirclesCount()) # -> 3

    Output of Example 2

    3
    
    3
    
    3
    • In Example 2, class Circle is passed as argument to getCirclesCount in both cases. i.e when it is called on objects and the class.