The difference between python class methods and ordinary methods

藏色散人
Release: 2019-07-03 09:45:03
Original
3840 people have browsed it

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

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

Output results

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

Look at the binding relationship:

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

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

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

Look at the binding relationship again:

print (a.get_class_apple) print (Apple.get_class_apple)
Copy after login

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

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!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!