Bound methods python

A bound method is the one which is dependent on the instance of the class as the first argument. It passes the instance as the first argument which is used to access the variables and functions. In Python 3 and newer versions of python, all functions in the class are by default bound methods.

Let’s understand this concept with an example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# use of bound methods
  
class A:
  
    def func(self, arg):
        self.arg = arg
        print("Value of arg = ", arg)
  
  
# Creating an instance
obj = A()  
  
# bound method
print(obj.func)

chevron_right


Output:

< bound method A.func of <__main__.A object at 0x7fb81c5a09e8>>

Here,

 obj.func(arg) is translated by python as A.func(obj, arg).

The instance obj is automatically passed as the first argument to the function called and hence the first parameter of the function will be used to access the variables/functions of the object.



Let’s see another example of the Bound method.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# use of bound methods
  
  
class Car:
    # Car class created
    gears = 5
  
    # a class method to change the number of gears 
    @classmethod
    def change_gears(cls, gears):
        cls.gears = gears
  
  
# instance of class Car created
Car1 = Car()
  
  
print("Car1 gears before calling change_gears() = ", Car1.gears)
Car1.change_gears(6
print("Gears after calling change_gears() = ", Car1.gears)
  
# bound method
print(Car1.change_gears)

chevron_right


Output:

Car1 gears before calling change_gears() =  5
Gears after calling change_gears() =  6
<bound method Car.change_gears of <class '__main__.Car'>>

The above code is an example of a classmethod. A class method is like a bound method except that the class of the instance is passed as an argument rather than the instance itself. Here in the above example when we call Car1.change_gears(6), the class ‘Car’ is passed as the first argument.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.