The method of the class in Python

Source: Internet
Author: User
Tags instance method

Reprinted from https://www.zhihu.com/question/22869546/answer/22933397 *************************

What is method?

function is a piece of code that can be called by name, and we can pass parameters in to get the return value. All parameters are explicitly passed in the past.
method is the combination of function and object. When we call a method, some parameters are implicitly passed in the past. This is detailed below.

# # # # Instancemethod # #
class Human (object):   ...:     def__init__(self, weight):   ...:         =  Weight     ...:def  get_weight (self):   ...:         return  Self.weight ...   : in     [6]: human.get_weightout[6]: <unbound method human.get_weight>

This tells us that Get_weight is a method that is not bound, what is called unbound? Keep looking.

In [7]: Human.get_weight ()--------------------------------------------------------------------------- TypeError                                 Traceback (Recent call last) in <module>()----> 1 human.get_weight () TypeError : Unbound method Get_weight () must is called with Human instance as first argument (got nothing instead)
未绑定的方法必须使用一个Human实例作为第一个参数来调用啊。那我们来试试
In [ten]: Human.get_weight (Human)out[10]: 45

Sure enough, but in general we are used to it.

In [all]: Person = Human (a) in[]: person.get_weight () out[12]: 45

The results of these two methods are identical. Let's look at the official documentation to explain the phenomenon.

When an instance attribute isReferenced that isn ' t a data attribute, itsclass  issearched. If the name denotes a validclassattribute that isA function object, a Method object iscreated by packing (pointers to) the instance object andThe function object just found togetherinchAn abstract object:this isThe method object. When the Method object iscalled with an argument list, a new argument list isConstructed fromThe Instance Object andthe argument list, andThe Function object isCalled with this new argument list.

The usual invocation method (Person.get_weight ()) is to pass the instance of the call hidden as a parameter self passed, and self is just an ordinary parameter name, not a keyword.

In []: person.get_weightout[]: <bound method Human.get_weight of <__main__. Human object at 0x8e13bec>> in[]: personout[]: <__main__. Human at 0x8e13bec>

We see that get_weight is bound to the instance object of person.

Summary below :

    1. Instance method is the combination of an instance object and a function.
    2. Using the class invocation, the first parameter explicitly passes past an instance.
    3. With an instance invocation, the instance of the invocation is passed implicitly as the first parameter.
# # # classmethod # #
class Human (object):   ...:     = [...:     @classmethod   ...:     def  get_ Weight (CLS):         ...:return  cls.weightin [2]: human.get_weightout[2 ]: <bound method Type.get_weight of <class'__main__. Human'>>

We see that Get_weight is a method that binds to the Human class. Call to see below

In [3]: human.get_weight () out[3]:[4]: Human (). Get_weight () out[4]: 12

Both classes and instances of the class can call Get_weight and call the results exactly as they are.

We see that weight is a property of the Human class and, of course, an instance of Human. Is the parameter that passes past the CLS a class or an instance?

 in [1]: class   Human (object): ...: Weight = 12 def  Span style= "color: #000000;" > Get_weight (CLS)::  print   CLS in [  2 <class   " __main__. Human   " >in [ 3]: Human (). Get_weight ()  <class   __main__. Human  ; 

We see that passing past is the Human class, not an instance of Human, and the result of the two-way invocation is no different. The CLS is just a normal function parameter that is implicitly passed through when invoked.

Summary below:

    1. Classmethod is a combination of class objects and functions.
    2. You can use an instance of the and class to invoke it, but you pass the class as an implied parameter past.
    3. Using a class to invoke Classmethod avoids the overhead of instantiating a class.
# # # staticmethod # #
In [1]:classHuman (object): ...: @staticmethod ...:defAdd (A, B): ...:returnA +b ...:defget_weight (self): ...:returnSelf.add (1, 2) in [2]: human.addout[2]: <function__main__.add>In [3]: Human (). addout[3]: <function__main__.add>In [4]: Human.add (1, 2) out[4]: 3In [5]: Human (). Add (1, 2) out[5]: 3

We see that add is just a normal function on both a class and an instance and is not bound to any particular class or instance. It can be called with an instance of a class or class, and there are no implicit arguments to pass in.

 is Human (). addout[6]: Truein [ is Human (). get_weightout[7]: False
Add is also the same object on two instances. Instancemethod is different, and each time a new Get_weight object is created.

Summarized under

    1. You can use Staticmethod when a function logically belongs to a class and does not depend on the properties of the class.
    2. You can use Staticmethod to avoid the overhead of creating an object each time you use it.
    3. Staticmethod can be called using instances of classes and classes. But not dependent on the state of the class and the instance of the class.
More examples and tricks to use: http://www.wklken.me/posts/2013/12/22/difference-between-staticmethod-and-classmethod-in-python.html http://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner/12179325#12179325

The method of the class in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.