In Python, the distinction between bound, unbound, and static methods is crucial for effective class design.
Unlike most other object-oriented languages, Python class methods are not static by default. When a class instance calls a member function, it is translated into a call to the unbound method with the instance as the first argument. For instance, consider the following code:
class Test(object): def method_one(self): print "Called method_one"
Calling method_one on an instance a_test will result in:
a_test.method_one() => Test.method_one(a_test)
To define a static method that is invoked on the class rather than an instance, use the @staticmethod decorator. This decorator instructs the metaclass to create an unbound method. For example:
class Test(object): @staticmethod def method_two(): print "Called method_two"
Now, both the instance and the class can invoke method_two:
a_test = Test() a_test.method_one() a_test.method_two() Test.method_two()
Calling method_two without an instance will not raise an error, unlike method_one, which expects an instance to be bound to it.
The above is the detailed content of What are the Differences between Bound, Unbound, and Static Methods in Python?. For more information, please follow other related articles on the PHP Chinese website!