Python : How to bind a function to an instance of a class in Python

python @

from types import MethodType

In Python, MethodType from the types module allows you to bind a function to an instance of a class. This can be useful when you need to add or change methods to an object dynamically.

Here is an example of how you might use it:

from types import MethodType

# Define a simple class
class MyClass:
    def __init__(self, name): = name

# Create an instance of the class
my_instance = MyClass('test_instance')

# Now define a new function outside of the class that we will bind as a method
def say_hello(self):
    print(f'Hello, {}!')

# Use MethodType to bind the function to the instance of the class
my_instance.say_hello = MethodType(say_hello, my_instance)

# Now you can call the new method

In this script, MethodType is used to bind the say_hello function to the my_instance object as a method. Now my_instance has a say_hello method that can access the name attribute of my_instance and print a greeting.

This is a rather contrived example and in practice, it’s unusual to need to add methods to objects like this in Python, as it’s often clearer and more maintainable to define all methods within the class definition. However, this feature can be useful in certain cases where you need to modify the behavior of objects on the fly or when working with dynamic or generated classes.

Refer more on python here :

Author: user

Leave a Reply