Define A Method Outside Of The Class Definition

Rate this post

Problem Statement: How to define a method outside of class definition in Python?

Example:

# Given Class
class Demo:
# Given Method
    def foo(self):
        x = 10
        return x

Can we create foo() outside of the class definition or maybe even in another module?

Introduction

We all know Python is an object-oriented programming language, and in Python, everything is an object including properties and methods. In Python, the class is like an object’s constructor for creating the objects. Thus, the variables can be defined inside the class, outside the class, and inside the methods in Python. The variables defined outside the class can be accessed by any method or class by just writing the variable name. So, in this article, we are going to learn how to define a method outside of the class definition.

What are Methods in Python?

As Python is an object-oriented programming language, it has objects that consist of properties. The attributes define the properties of these objects, and the behavior is defined using methods. Methods are reusable pieces of code called at any point in the program and are defined inside the class. Every method is associated with the class and can be invoked on the instances of that class.

For example, we can consider a class named ‘Students’ that contains properties like name, id , and rank. The class also holds behaviors like run, jump , and swim. Suppose an object Stud1 has the following properties:

Name- Finxter
Id – 1020
Rank- 1

Here’s how you can assign the values:

class Student:
    def __init__(self, name, id, rank):
        self.name = name
        self.id = id
        self.rank = rank

    def run(self):
        print(f'{self.name} is a cross country champion!')

    def jump(self):
        print(f'{self.name} with the following ID: {self.id} is a high jumper!')

    def swim(self):
        print(f'{self.name} secured rank {self.rank} in swimming.')


stud1 = Student('Finxter', 1020, 1)
stud1.run()
stud1.jump()
stud1.swim()

Output:

Finxter is a cross country champion!
Finxter with the following ID: 1020 is a high jumper!
Finxter secured rank 1 in swimming.

The above example demonstrated the traditional way of adding functionality (methods) to a Python class. Here, the methods were defined inside the class body. Now, let’s say that you want to define a method outside the class body. How will you do so? Let’s dive into the different approaches to unearth the answers to this question.

Define The Method Outside and Use Inside Class Body

The idea here is to define the method outside the class and then use it inside the class body, as shown below.

Example 1:

# Defining the method outside the class
def foo(self):
    print("Method foo executed")
    x = 10
    print("Value of x = ", x)
# Using the method inside the class body
class Demo:
    my_method = foo

You can also define a class first and then add a method or function to it from outside its body, as shown below.

Example 2:

# Define the class
class Demo:
    pass


# Define the method outside the class 
def foo(self):
    print("Method foo executed ")

# Pass the method to the class
Demo.method1 = foo

Caution: We can even define the functions, methods, and classes in different modules if we want to. However, it is advisable to use example 1 rather than example 2 (defining the class in one module, then importing it into another module and further adding methods to it dynamically) because the class objects may behave differently depending on whether the module has been imported or not.

There’s another way to define the function outside of a class and then further add it. But there is a difference in assigning the function to the instance object or the class. Look at the following example to understand the subtle difference:

class Demo1(object):
    def __init__(self, bar):
        self.func = 'Finxter'
        Demo1.funcbar = bar


class Demo2(object):
    def __init__(self, bar):
        self.func = 'Finxter'
        self.funcbar = bar


def bar(self):
    return 'Welcome' + self.func

Explanation: Let’s understand what’s happening here.

  • In case of class Demo1 , funcbar is just like any other normal method that is bound to the instance of the class. Let’s have a look at what this looks like –
  • In case of class Demo 2, funcbar is simply a reference to the bar function, i.e., it is not a bound function. Thus, we must pass the instance for this function for it to work properly.

Using Inheritance

You can even use the methods of a class in another class. In the following example we have a class Helper with certain methods defined within it. All the methods of the class Helper can be inherited by the class Demo as shown below.

class Helper(object):
    # Subtraction function
    def subs(self, a, b):
        return a - b
    
    # Addition function
    def add(self, a, b):
        return a + b
    
    # Multiplication function
    def mul(self, a, b):
        return a * b
        
    # Division function
    def div(self, a, b):
        return a / b
# Given class
class Demo(Helper):
    def __init__(self):
        Helper.__init__(self)
        print("The addition of numbers is", self.add(10, 5))
        print("Subtraction of numbers is", self.subs(60, 15))
        print("Multiplication of numbers is", self.mul(5, 9))
        print("The division of numbers is", self.div(100, 50))
# Main method
if __name__ == '__main__':
    obj = Demo()

Output:

The addition of numbers is 15
Subtraction of numbers is 45
Multiplication of numbers is 45
The division of numbers is 2.0

Related Read: Inheritance in Python

Conclusion

To sum things up, it is absolutely possible to have functions outside classes in Python. If you want to gather a group of functions in one box then you can simply put them together in the same module. Further, you can nest modules within packages. It is recommended that you should use classes when you have to create a new datatype and don’t just use it to group functions together.

That’s it for this discussion and I hope it helped you. Please stay tuned and subscribe for more interesting articles and discussions in the future. Happy learning!


Article by Shubham Sayon and Rashi Agarwal