Home  >  Article  >  Backend Development  >  The difference between python class methods and ordinary methods

The difference between python class methods and ordinary methods

藏色散人
藏色散人Original
2019-07-03 09:45:033793browse

The difference between python class methods and ordinary methods

The difference between python class methods and ordinary methods

The following uses examples to illustrate the differences.

First, define a class, including 2 methods:

class Apple(object):
        def get_apple(self, n):
                print "apple: %s,%s" % (self,n)
        @classmethod
        def get_class_apple(cls, n):
                print "apple: %s,%s" % (cls,n)

Common methods of the class

Common methods of the class need to be called by instances of the class .

a = Apple()
a.get_apple(2)

Output results

apple: <__main__.Apple object at 0x7fa3a9202ed0>,2

Look at the binding relationship:

print (a.get_apple)
<bound method Apple.get_apple of <__main__.Apple object at 0x7fa3a9202ed0>>

The ordinary methods of the class can only be used with instances of the class. If you use a class to call a normal method, the following error occurs:

Apple.get_apple(2)
Traceback (most recent call last): File "static.py", line 22, in <module> Apple.get_apple(2) TypeError: unbound method get_apple() must be called with Apple instance as first argument (got int instance instead)

Class method

Class method means that the method is bound to the class.

a.get_class_apple(3)
Apple.get_class_apple(3)
apple: <class &#39;__main__.Apple&#39;>,3
apple: <class &#39;__main__.Apple&#39;>,3

Look at the binding relationship again:

print (a.get_class_apple) print (Apple.get_class_apple)

The output results are the same when using instances and calling classes.

<bound method type.get_class_apple of <class &#39;__main__.Apple&#39;>> <bound method type.get_class_apple of <class &#39;__main__.Apple&#39;>>

Related recommendations: "Python Tutorial"

The above is the detailed content of The difference between python class methods and ordinary methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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