What are the Differences between Bound, Unbound, and Static Methods in Python?

Barbara Streisand
Release: 2024-11-15 10:19:02
Original
825 people have browsed it

What are the Differences between Bound, Unbound, and Static Methods in Python?

Class Method Differences in Python: Bound, Unbound, and Static

In Python, the distinction between bound, unbound, and static methods is crucial for effective class design.

Bound and Unbound Methods

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"
Copy after login

Calling method_one on an instance a_test will result in:

a_test.method_one()
=> Test.method_one(a_test)
Copy after login

Static Methods

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"
Copy after login

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()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template