The binding method and non-binding method of fully parsing Python class

Source: Internet
Author: User

There are two types of methods in a class:
    • Binding method
    • Non-binding method
First, binding Method 1. Binding Methods for objects

First we define a knowledge point, in which a method or function in a class is bound to the object by default. Below, we use an example to slowly parse the application of the binding method.

classpeople:def __init__(self,name,age): Self.name=name Self.age= AgedefTalk (self):PassP= People ('Xiaohua', 18)Print(p.talk) output results:<Bound Method Peopl E. Talkof <__main__.People ObjectAt 0x000000f802c69358>>

From the above output, the method in the talk () class is bound to the object used. Below, I'm looking at a different situation.

classpeople:def __init__(self,name,age): Self.name=name Self.age= AgedefTalk ():PassP= People ('Xiaohua', 18)Print(p.talk) output results:< bound Method People.talk of <__main__. PeopleObjectAt 0x000000ff68f39358>>

Now, let's remove the arguments for the talk () function, and the result is the same as above. This means that either the method in the class or the function in the class is bound to the object by default. The advantage of binding to an object is that it does not have to be passed into the object manually. Objects are automatically passed into the class. If you don't believe us, let's take a look at the following example:

classpeople:def __init__(self,name,age): Self.name=name Self.age= AgedefTalk ():PassP= People ('Xiaohua', 18)Print(People.talk)Print(p.talk) output results:<function People.talkAt the 0x000000c54e3d0a60> class to invoke just as a function using <bound method People.talk of <__main__. People object at 0x000000c54e249358>> instead of calling the binding method

It is good to note that if a class calls a method in a class, then this method is just a function, and since it is a function, it will not have the function of automatically passing the value. Take a look at the following code:

classpeople:def __init__(self,name,age): Self.name=name Self.age= AgedefTalk (self):PassP= People ('Xiaohua', 18) People.talk ()1P.talk ()2#error at code 1Talk () Missing 1 required positional argument:' Self'#Code 2 Normal

From the output above, when the class calls the method in the class I, is not automatically passed the value, that is, the function has a few parameters, we have to pass in a few parameters. If you want the result to work properly, pass the parameter one by one in when the class name calls Talk (). That

People.talk (312312)

This parameter can be arbitrary, but it must be passed in. And, when the object calls the method in the class, it is not passed, as the above 2 performs normally. Now that you know the difference, let's take a look at the following code:

 class   people:  def  __init__   (Self,name,age): Self.name  = name Self.age  = age def   talk ():  pass  p  = people ( " xiaohua  , 18) People.talk ()  1 Span style= "color: #000000;" >p.talk ()  2#   1 normal execution  #   Talk () takes 0 positional arguments if 1 was given 

From the output, people calls the Talk () method, does not need to pass arguments, and when the object calls talk (), because the object calls its own binding method, the object is automatically passed as the first parameter, so when the class in the talk () method without parameters, And you give it another, obviously will be an error.

  To sum up, we can draw the following conclusions:

    1. The methods and functions in any class are bound to the objects used;

2. The binding method has the function of automatic value transfer. The value passed in is the object itself.

3. If a class wants to invoke a binding method, it must follow the parameter rules of the function, and with several arguments, several parameters must be passed.

Smart you, you might ask, since the methods in the class are bound to the object used, then there is no way to bind to the class use it?

The answer is, of course there is!

2. Binding Methods for classes

Since the methods in the class are bound to the objects by default, we take a little action to unbind the binding method in the class from the object binding to the class.

In Python, the @classmethod method is introduced to bind a method in a class to a class. Here's a look at the code:

 class   people: @classmethod  def   talk (CLS):  pass  p  = people ()  print   (People.talk)  #   output  <bound method  People.talk of <class   __main__. People    " >> 

As can be seen from the above results, we have added an adorner that binds the method bound to the object in the class to the class. We have previously analyzed that if a method binds to a person, the caller is automatically passed to the function as the first parameter when the function is called. However, a method that is bound to a class is a little different from binding to an object method:

classpeople:def __init__(self,name): Self.name=name @classmethoddefTalk (CLS):PassP= People ('Xiaohua')Print(People.talk)Print(P.talk)#Output Results<Bound MethodPeople.talk of <class '__main__. people '>><Bound MethodPeople.talk of <class '__main__. people '>>

That is, when an object calls a binding method of a class, it also defaults to passing the class as a parameter! so the following is normal, and not because this method is bound to the class body, and the object call does not pass parameters, error!

class people:    @classmethod    def talk (CLS):        pass= people () People.talk () P.talk ( )

However, if the talk () does not have parameters, the following code will error.

class people:    @classmethod    def Talk ():        pass= people () People.talk () P.talk ()# Error results talk () takes 0 positional arguments but 1 was given

The result of both errors is consistent, which means that when an object invokes a class's binding method, it is automatically passed in, and does not have to follow the rules passed by the function arguments.

For the binding method in the class, and basically the two, no matter how the change, as long as the following rules are kept in mind, it is no longer wrong to encounter this situation.

A method in a class is bound to an object by default, and when the object invokes the binding method, the object is automatically passed in as the first argument, and the class is called, and the rule must follow the corresponding rules for the function parameter one by one, and there are several parameters that must be passed. If a method uses the @classmethod adorner, then this method binds to the class, and the class is passed in as the first parameter, whether it is an object invocation or a class call.

Class Binding Method Application Example: Single-case mode!

Second, non-binding method

It says that the methods in the class are either bound to the object or used by the class, so are there any functions that are not bound to the two?

Answer: Of course, Python gives us @staticmethod, can unbind the relationship, the method in a class into a normal function.

Let's take a look at the code example:

ImportHashlibImport TimeclassMySQL:def __init__(self,host,port): Self.id=self.create_id () self.host=host Self.port=Port @staticmethoddefCREATE_ID ():#It 's a common tool .M=HASHLIB.MD5 (str (Time.clock ()). Encode ('Utf-8'))        returnm.hexdigest ()Print(mysql.create_id)#<function mysql.create_id at 0x0000000001e6b9d8> #查看结果为普通函数Conn=mysql ('127.0.0.1', 3306)Print(conn.create_id)#<function mysql.create_id at 0x00000000026fb9d8> #查看结果为普通函数

From the above output, we can see that using the @staticmethod decorated a function, then this function is no different from the normal function. Since it is a normal function, then follow the function parameter passing rule, there are several parameters to pass several parameters.

  

  

The binding method and non-binding method of fully parsing Python class

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.