Python Learning _12_ methods and class customization

Source: Internet
Author: User

Method

In the previous essay, we briefly mentioned some of the methods of the class: __init__ () and so on, and a brief description of the difference between methods and functions.

A method is a function defined inside a class, and a method is an object, so the method is a property of the class, which is why the method of the instance is present in the class definition. In Ruby, the method is definitely present in the class, the single-piece method of the instance exists in the single-piece class, there is no single-piece class in Python, and the method nature is also a property, so the method of the instance can also exist in itself, and when the method is called, it follows the search order of the namespace. However, the method and the general nature of the existence of any difference:

From types Import Methodtype
Class MyClass:
? ? # @staticmethod
? ? def my_method (self):
? ? ? ? Print ("This is a class method")
obj = MyClass ()
Print (' Obj_m ', ID (obj.my_method))
#obj2 = MyClass ()
#print (' obj2_m ', ID (obj2.my_method))
#a = Obj.my_method
Print (' Cls_m ', ID (myclass.my_method))
def my_method (self):
? ? Print ("This is a obj method")
Obj.my_method = Methodtype (my_method,obj)
Print (' Obj_m ', ID (obj.my_method))
Print (' Cls_m ', ID (myclass.my_method))
def my_method (self):
? ? Print ("This is a obj method2")
Obj.my_method = Methodtype (my_method,obj)
Print (' Obj_m ', ID (obj.my_method))

The results are as follows:

Obj_m 4337531000
Cls_m 4337792688
Obj_m 4337531000
Cls_m 4337792688
Obj_m 4337531792

As you can see, a normal function is set at the beginning, and the result is that the reference to the function in the class is not the same as the reference to the function in the object, and when the function is modified in the object, the first modification does not change the reference, but the reference changes when the second modification, and the reference of the class to the function will not Since the second modification does change the reference, it is true that the function is a non-modifiable type (which can be obtained through a simpler experiment), and why did the first change to the object not change its reference? In fact, because the function of the object here and the function of the class is not the same reference, when the first time the function of the object is changed, the original object's function reference number becomes 0, the address is reclaimed by the system, when we define a function of the same name to the object, and then the same address, actually changed the reference. You can verify by increasing the number of references to the method (the fourth comment, if you remove the comment, the reference will be different).

Well, there's a lot of detours going back to the point: the function of the object and the function of the class are not the same reference at first, because the function is passed to the function when the object is called (the emphasis here is that the function is the same as even if it is removed), so the function that the object calls is a function that is bound. The classes invoke functions that are not bound, so their references are different. The reference to a method is only made different by invoking a binding, which has no effect on the reference to the function (minus the comment on line second to third can be experimented with).

To verify, you can experiment with the following code:

Class MyClass:
? ? Pass
Class MyClass2:
? ? Pass
Print (ID (myclass2.__new__))
Print (ID (myclass.__new__))
Print (ID (type.__new__))

Static Methods and Class methods

In the first line of comments in the above code, there is a @staticmethod adorner, if you remove the comment, you will find that the class and object reference to the function is the same, this is the static method, the static method is equal to the class and object, but does not mean that the exact same, Because class-to-function calls still don't come with bindings: If you call self in a static method, you still don't need to pass in to the object, and for the class, you must pass in an object for invocation (which can pass in MyClass). Because only one of the functions in the MyClass namespace is called, there is no binding for MyClass.

When an object calls a method without explicitly passing in itself, because the method is defined in the class, self means the object after the class is instantiated, and when the object calls its own method of the class, the interpreter helps to pass the object to the method.

The class method refers to the first parameter as the class itself, without a name like self, but generally using the CLS as the variable name:

Class MyClass:
? ? @classmethod
? ? def a_method (CLS):
? ? ? ? Print (CLS)
Myclass.a_method ()

At this point, you can also not pass in an object explicitly.

Class customization

The so-called class customization in Python is the implementation of a specific method for a class that has some specific properties, or can perform some specific actions on it. These special methods start with a double underscore and end with a double underscore. In fact, the __init__ method is the most basic custom class of special methods, through the __init__ method can be customized to instantiate the class instance process.

Some of the more commonly used customizations are:

1. Customize the __str__ method so that instances of the class can be converted to strings through STR (), and because print is actually called STR (), the printed format can be customized;

2. Customize the __len__ method to customize the value returned when Len () is called;

3. Customizing the __iter__ method, you can make an instance of the class an iterative object, at this point, you need to implement the __next__ method (Python2 in the next method), make the iterative process complete execution, in the __next__ method, specify the stopiteration error, To terminate the iteration.

4. Custom __cmp__ methods, __lt__, __le__, __gt__, __ge__, __eq__, __ne__ and other methods can be customized to compare the size of the rules;

5. Custom __*add__, __*sub__ and so on the numerical operation method, may customize the class instance the +-*/and so on operation, * indicates exists __add__, __radd__, __iadd__ and so on many methods, the default method calculates from left to right, the method beginning with R is calculated from right to left, I begins with a combination of the left associative operator and the assignment, similar to + =

6. Customizing the __call__ method allows instances of the class to be called

Wait a minute

If you want to get a more specific example, the following articles should be helpful:

Http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/ 0013946328809098c1be08a2c7e4319bd60269f62be04fa000

Python Learning _12_ methods and class customization

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.