Bound methods
If a function is an attribute of class and it is accessed via the instances, they are called bound methods. A bound method is one that has ‘self
‘ as its first argument. Since these are dependent on the instance of classes, these are also known as instance methods.
Need for these bound methods
The methods inside the classes would take at least one argument. To make them zero-argument methods, ‘decorators
‘ has to be used. Different instances of a class have different values associated with them.
For example, if there is a class “Fruits”, and instances like apple, orange, mango are possible. Each instance may have different size, color, taste, and nutrients in it. Thus to alter any value for a specific instance, the method must have ‘self’ as an argument that allows it to alter only its property.
Example:
class sample( object ): # Static variable for object number objectNo = 0 def __init__( self , name1): # variable to hold name self .name = name1 # Increment static variable for each object sample.objectNo = sample.objectNo + 1 # each object's unique number that can be # considered as ID self .objNumber = sample.objectNo def myFunc( self ): print ( "My name is " , self .name, "from object " , self .objNumber) def alterIt( self , newName): self .name = newName def myFunc2(): print ( "I am not a bound method !!!" ) # creating first instance of class sample samp1 = sample( "A" ) samp1.myFunc() # unhide the line below to see the error # samp1.myFunc2() #----------> error line # creating second instance of class sample samp2 = sample( "B" ) samp2.myFunc() samp2.alterIt( "C" ) samp2.myFunc() samp1.myFunc() |
Output:
My name is A from object 1 My name is B from object 2 My name is C from object 2 My name is A from object 1
In the above example two instances namely samp1 and samp2 are created. Note that when the function alterIt()
is applied to the second instance, only that particular instance’s value is changed. The line samp1.myFunc() will be expanded as sample.myFunc(samp1). For this method no explicit argument is required to be passed. The instance samp1 will be passed as argument to the myFunc(). The line samp1.myFunc2() will generate the error :
Traceback (most recent call last): File "/home/4f130d34a1a72402e0d26bab554c2cf6.py", line 26, in samp1.myFunc2() #----------> error line TypeError: myFunc2() takes 0 positional arguments but 1 was given
It means that this method is unbound. It does not accept any instance as an argument. These functions are unbound functions.
Bound, unbound, and static methods in Python
Methods in Python are like functions except that it is attached to an object.The methods are called on objects and it possibly make changes to that object. These methods can be Bound, Unbound or Static method. The static methods are one of the types of Unbound method. These types are explained in detail below.
Contact Us