Bound, unbound, and static methods in Python
Last Updated :
31 Dec, 2019
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.
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:
Python3 1==
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.
Unbound methods and Static methods
Methods that do not have an instance of the class as the first argument are known as unbound methods. As of Python 3.0, the unbound methods have been removed from the language. They are not bounded with any specific object of the class. To make the method
myFunc2() work in the above class it should be made into a
static method
Static methods are similar to class methods but are bound completely to class instead of particular objects. They are accessed using class names.
Need for making a method static
Not all the methods need to alter the instances of a class. They might serve any common purpose. A method may be a utility function also.
For example, When we need to use certain mathematical functions, we use the built in class
Math
. The methods in this class are made static because they have nothing to do with specific objects. They do common actions. Thus each time it is not an optimized way to write as:
math=Math()
math.ceil(5.23)
So they can be simply accessed using their class name as
Math.ceil(5.23)
.
A method can be made static in two ways:
- Using staticmethod()
- Using decorator
Using staticmethod(): The
staticmethod()
function takes the function to be converted as its argument and returns the static version of that function. A static function knows nothing about the class, it just works with the parameters passed to it.
Example:
Python3 1==
class sample():
def myFunc2(x):
print("I am", x, "from the static method")
sample.myFunc2 = staticmethod(sample.myFunc2)
sample.myFunc2("A")
Output:
I am A from the static method
Using decorators: These are features of Python used for modifying one part of the program using another part of the program at the time of compilation. The decorator that can be used to make a method static is
@staticmethod
This informs the built-in default metaclass not to create any bound methods for this method. Once this line is added before a function, the function can be called using the class name. Consider the example taken for the Bound method where we encountered an error. To overcome that, it can be written as:
Python3 1==
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
# using decorator to make the method static
@staticmethod
def myFunc2():
print("I am not a bound method !!!")
# creating first instance of class sample
samp1 = sample("A")
samp1.myFunc()
sample.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
I am not a bound method !!!
My name is B from object 2
My name is C from object 2
My name is A from object 1
Here, the line
sample.myFunc2() runs without any error and the print() within it works perfectly and gives the output
I am not a bound method!!!
Similar Reads
Class method vs Static method in Python In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python.What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated a
5 min read
Matplotlib.axes.Axes.set_xbound() in Python Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
2 min read
Matplotlib.axes.Axes.set_ybound() in Python Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
2 min read
Dunder or magic methods in Python Python Magic methods are the methods starting and ending with double underscores '__'. They are defined by built-in classes in Python and commonly used for operator overloading. They are also called Dunder methods, Dunder here means "Double Under (Underscores)". Python Magic MethodsBuilt in classes
7 min read
Extend Class Method in Python In Python, class methods are functions that are bound to the class rather than the instance of the class. This means they receive the class (cls) as the first argument instead of the instance (self). Extending a class method refers to enhancing or customizing the behavior of an inherited class metho
3 min read
Singleton Method - Python Design Patterns Prerequisite: Singleton Design pattern | IntroductionWhat is Singleton Method in PythonSingleton Method is a type of Creational Design pattern and is one of the simplest design patterns available to us. It is a way to provide one and only one object of a particular type. It involves only one class t
5 min read
Namespaces and Scope in Python What is namespace:A namespace is a system that has a unique name for each and every object in Python. An object might be a variable or a method. Python itself maintains a namespace in the form of a Python dictionary. Let's go through an example, a directory-file system structure in computers. Needle
4 min read
Python __add__() magic method Python __add__() function is one of the magic methods in Python that returns a new object(third) i.e. the addition of the other two objects. It implements the addition operator "+" in Python. Python __add__() Syntax Syntax: obj1.__add__(self, obj2) obj1: First object to add in the second object.obj2
1 min read
Python staticmethod() Function Python staticmethod() function is used to convert a function to a static function. Static methods are independent of class instances, meaning they can be called on the class itself without requiring an object of the class.Example:Pythonclass Utility: def msg(name): return f"Hello, {name}!" msg = sta
6 min read
Class or Static Variables in Python All objects share class or static variables. An instance or non-static variables are different for different objects (every object has a copy). For example, let a Computer Science Student be represented by a class CSStudent. The class may have a static variable whose value is "cse" for all objects.
9 min read