Using an example to analyze the parameter transfer process of method in Python _python

Source: Internet
Author: User
Tags instance method in python

What is method?

A function is a piece of code that can be called by the name, and we can pass the parameter in and get the return value. All parameters are communicated in a clear past.
method is a combination of a function and an object. When we call a method, some parameters are implicitly passed in the past. Details are provided below.
Instancemethod

In [5]: Class Human (object)::   def __init__ (self, weight):
  ...:     self.weight = Weight
  ...:   def get_weight (self):
  ...: return     self.weight ...
  : in  
 
[6]: Human.get_weight
out[6]: < Unbound method human.get_weight>

This tells us that Get_weight is a method that is not bound, what is called unbound? Go ahead and watch.

In [7]: Human.get_weight ()
---------------------------------------------------------------------------
TypeError                 Traceback (most recent call last)
/home/yao/learn/insight_python/< Ipython-input-7-a2b2c5cd2f8d> in <module> ()
----> 1 human.get_weight ()
 
Typeerror:unbound method Get_weight () must is called with Human instance as-a-argument (got nothing instead)

An unbound method must be invoked with a human instance as the first argument. Let's try it.

In [45]: Human.get_weight (Human)
out[10]:

It was a success, but in general we used it.

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

The results of these two methods are identical. Let's look at how the official document explains this phenomenon.

When an instance attribute was referenced that isn ' t a data attribute, the its class is searched.
If the name denotes a valid class attribute that's a function object, a method object is
Created by packing (pointers to) The instance object and the function object just found
In a abstract Object:this is the method object. When the "method" object is called with an
Argument list, a new argument list is constructed from the instance object and the argument list,
And the function object is called with this new argument list.

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

in [+]: Person.get_weight
out[13]: <bound method Human.get_weight of <__main__. Human object at 0x8e13bec>> in
 
[?]: Person
out[14]: <__main__. Human at 0x8e13bec>

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

    1. Instance method is the combination of instance object and function.
    2. Using class invocation, the first parameter explicitly passes an instance of the past.
    3. Using an instance invocation, an instance of the invocation is passed through implicitly as the first argument.

Classmethod

In [1]: Class Human (object):
  ...:   weight = ...:   @classmethod
  ...:   def get_weight (CLS):
  ...: return     cls.weight in
 
[2]: Human.get_weight
out[2]: <bound method Type.get_weight of < Class ' __main__. Human ' >>

We see that get_weight is a method bound to the class of Human. Call down to see

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

Instances of classes and classes can call Get_weight and the invocation results are exactly the same.
We see that weight is an attribute of the Human class, and of course the Human instance. That passes past parameters. Is the CLS a class or an instance?

In [1]: Class Human (object):
  ...:   weight = ...:   @classmethod
  ...:   def get_weight (CLS):
  ...:     print cls in
 
[2]: Human.get_weight ()
<class ' __main__. Human ' > in
 
[3]: Human (). Get_weight ()
<class ' __main__. Human ' >

We see that the passing past is all Human classes, not Human instances, and the results of the two invocations are not any different. The CLS is just an ordinary function parameter, which is implicitly passed over when invoked.
summed up

    1. Classmethod is a combination of class objects and functions.
    2. You can use instances of classes and classes to invoke, but all pass the class as a suppressed parameter past.
    3. Using a class to invoke Classmethod avoids the overhead of instantiating the class.

Staticmethod

In [1]: Class Human (object):
  ...:   @staticmethod ...:   def add (A, B):
  ...: return     A + b ...
  :   def get_weight (self):
  ...: Return     self.add (1, 2) in
 
[2]: Human.add
out[2]: <function __ Main__.add> in
 
[3]: Human (). Add
out[3]: <function __main__.add>
 
in [4]: Human.add (1, 2)
OUT[4]: 3
 
in [5]: Human (). Add (1, 2)
Out[5]: 3

We see that add is just a normal function on either a class or an instance, and is not bound to any particular class or instance. You can use a class or an instance of a class to invoke, and there is no incoming of any suppressed parameters.

In [6]: Human (). Add-Human (). Add
out[6]: True in
 
[7]: Human (). Get_weight is Human (). Get_weight
Out[7]: False

Add is the same object on two instances. Instancemethod is different, and each time a new Get_weight object is created.
Summary of

    1.     You can use Staticmethod when a function logically belongs to a class and does not depend on the properties of the class.
    2.     Use Staticmethod to avoid the overhead of creating an object each time it is used.
    3.     Staticmethod can be invoked using instances of classes and classes. However, it does not depend on the state of instances of classes and classes.
Related Article

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.