Home >Backend Development >Python Tutorial >What are the differences between unbound, bound, and static methods in Python classes?
Class Method Differences in Python: Unbound, Bound, and Static
In Python, class methods can be categorized into three types: unbound, bound, and static. Understanding their distinctions is crucial for effective object-oriented programming.
Bound Methods
Bound methods are those that require an instance of the class as the first argument when invoked. For example, the method_one method in the following code is a bound method:
class Test(object): def method_one(self): print "Called method_one"
To call a bound method, an instance of the class must be provided. For instance:
a_test = Test() a_test.method_one()
Unbound Methods
Unbound methods are essentially class methods that have not been bound to an instance of the class. In Python, all class methods are initially unbound. For example, the method_two method in the code snippet below is an unbound method:
class Test(object): def method_two(): print "Called method_two"
Unbound methods cannot be called directly on instances of the class. Instead, they must be bound to an instance before being invoked. This can be achieved by using the class name as the first argument, as shown below:
Test.method_two()
Static Methods
Static methods are methods that are not bound to an instance of a class and do not require an instance as the first argument. They are declared using the @staticmethod decorator. For instance:
class Test(object): @staticmethod def method_three(): print "Called method_three"
Static methods can be called directly on the class or on an instance of the class. For example:
Test.method_three() a_test = Test() a_test.method_three()
Summary
In summary, the key difference between class methods in Python lies in their binding status. Bound methods require an instance as the first argument, unbound methods must be bound to an instance before being invoked, and static methods are not bound to instances and do not require an instance as an argument.
The above is the detailed content of What are the differences between unbound, bound, and static methods in Python classes?. For more information, please follow other related articles on the PHP Chinese website!