Home > Article > Backend Development > 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 '__main__.Apple'>,3 apple: <class '__main__.Apple'>,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 '__main__.Apple'>> <bound method type.get_class_apple of <class '__main__.Apple'>>
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!