Bound methods in Python

The Bound methods are the methods defined in a class. The bound methods are bound to the class in which they are defined. They take an instance of their class along with the other arguments as its parameters. Bound methods differ from the other unbound methods in their first parameter. Bound methods’ first parameter must be the instance, whereas, for unbound methods, the parameters are optional. If the parameters exist, the first one can be of any type.

class Class:
    def boundMethod(self,param1):
        print("I'm a method bound to Class. Here is my Class's Reference:", self,'Parameter:',param1)
instance = Class()
instance.boundMethod(10) # same as Class.boundMethod(instance,10)

While most use self as the name for the first parameter, it can be named anything.

class Class:
    def boundMethod(instance,param1):
        print("I'm a method bound to Class. Here is my Class's Reference:", instance,'Parameter:',param1)
instance = Class()
instance.boundMethod(10) # same as Class.boundMethod(instance,10)

Both the above code snippets give the same output:

I'm a method bound to Class. Here is my Class's Reference: <__main__.Class object at 0x7f73cd2d8ac0> Parameter: 10
class Class:
    def boundMethod():
        print("I'm a method bound to Class")
instance = Class()
instance.boundMethod() # same as Class.boundMethod(instance)

If the first argument is skipped, Python will raise a TypeError:

Traceback (most recent call last):
File "boundmethods.py", line 20, in <module>
instance.boundMethod() # same as Class.boundMethod1(instance,10)
TypeError: boundMethod() takes 0 positional arguments but 1 was given

To fix the error, parameters and arguments have to be passed correctly. It can also be fixed using a @staticmethod decorator. If @staticmethod decorator is used, it becomes a static method, where instead of one method for an instance of a class, one method for the entire class would be created.

class Class:
    @staticmethod
    def boundMethod(param1):
        print("I'm a method bound to Class,",'Parameter:',param1)
instance = Class()
instance.boundMethod(10) # same as Class.boundMethod(10)

This produces the output :

I'm a method bound to Class, Parameter: 10

Leave a Reply

Your email address will not be published. Required fields are marked *