Part.6 of the Face object of 8.python (supplementary authorization and inheritance concept)

Source: Internet
Author: User
Tags wrapper

I. What is the "wrapper" for a class in Python.

(In simple terms, wrapping means adding or modifying the functionality of a class by inheriting the attributes of the class)

For example, Python provides a number of standard data types, as well as many built-in methods, and in some scenarios we need to customize the type of data we need based on standard data types, add or rewrite some class methods, and in doing so, we need to use classes to inherit the relevant knowledge. (Python's standard class can be processed two times by "wrapping" this way.) )

Example 1: Add a function to the list list class of Python, this function can see the most middle element in the lists, and modify the Append method in the listing class, when appending an element to a list using append, the appended data type is only allowed to be a string, not a number.

Now to complete the two requirements of Example 1, you can do this through the "wrapping" (inheritance) approach.


#!/usr/bin/python2.7

#-*-Coding:utf-8-*-

Class New_list (list): #新定义了一个类叫new_list这个类继承了python内置的list类

def append (self, p_object): # Defines a Append method that modifies the Append method inherited from the list class

If not isinstance (P_OBJECT,STR): # Determines whether the passed in value is a string type

Print "Non-string cannot be added to this modern list using append" # If this line of text is not printed

Else

Super (New_list,self) append (p_object) # If it is a string type, use the Super keyword to call the New_list parent class, the Append method in the list class.

def show_mid (self): # This is the new method.

index = int (len (self)/2)

Print Self[index]

Next, test the functionality of the New_list class.

NL1 = New_list () # Initializes an instance with the New_list class, with the name NL1.

Next, add a non-string type element to the NL1 list to see what the effect will be.

Nl1.append (123) # Adds a non-string element.


Output:

Non-string cannot be added to this modern list using append


Next, pass in the elements of several string types.

NL1 = New_list ()

Nl1.append ("one")

Nl1.append ("both")

Nl1.append ("three")

Nl1.append ("four")

Nl1.append ("five")

Print NL1

Output:

[' One ', ' one ', ' three ', ' four ', ' five ']

# Elements of the string type were successfully added to the list.

As can be seen from the example, the function of the Append method of the New_list parent list has been successfully modified.


Next, test the new Show_mid method on the list basis.

Print NL1

Output:

[' One ', ' one ', ' three ', ' four ', ' five ']


Nl1.show_mid ()

Output:

Three # successfully printed out the most intermediate element in the list.


Two. What is authorization?

Authorization is a feature of "packaging", when you want to "wrap" a class, it is usually to do some customization of the existing class, the function of the existing class is modified (add, delete, modify), but "authorization" is not implemented by inheritance, it has no relationship with inheritance, authorization is through the overwrite __ The getattr__ method to achieve this.

(You can also interpret "authorization" as another form of a "wrapper" class)


When do I need to use authorization?

Take the file object in Python For example, we all know that the file in Python is also an object, if you want to instantiate a file object, you need to use the open function to complete, now there is a requirement, is to define a class for the file operation, and modify the write method of this class, When you write a file by using this class of your own definition, write the current time to the file (that is, add a function to the Wirte party to write the current time).


#!/usr/bin/python2.7

#-*-Coding:utf-8-*-

Import time

Class File_handle (object): #自己定义了一个处理文件的类file_handle.

def __init__ (self,file_path,mode= "R"): # Create a file handle from the open function by constructing the method

Self.file_open = open (File_path,mode)

def write (Self,line):

Date = Time.strftime ('%y-%m-%d%T ')

Self.file_open.write ("%s%s"% (Date,line)) # invokes the Write method of the file handle and writes the contents to the file.

def __getattr__ (self, item): # When a method is not found in a class, the __getattr__ method is triggered.

# This method is triggered when the Read method is not found in the Write method.

Return GetAttr (Self.file_open,item) # finds the original function of the file handle by reflecting it through the GetAttr function.

F1 = File_handle (' a.txt ', mode= "R")



In the File_handle class, the Read method is not defined, so let's try to see if the contents of the file can be read.

F1 = File_handle (' a.txt ', mode= "R") # initializes the object, and passes the argument, opening the A.txt file with the class you created.

F1.read ()

Output:

Hello world\n

#成功调用了文件对象的read方法, and there is no way to use inheritance.


#接着在试着调用wirte方法在文件中写内容 to see if the original write function of the file object has been changed.

F1 = File_handle (' a.txt ', mode= "w")

F1.seek (0)

F1.write ("aaaaaaaaaaa\n")

F1.write ("bbbbbbbbbbb\n")

F1.flush ()

# write two lines of content in the file, then open the file to see if the content and time are written inside the file.

The contents of the file are as follows:

2017-04-19 20:59:23 AAAAAAAAAAA

2017-04-19 20:59:23 BBBBBBBBBBB

# successfully modified the write function of the file object by means of authorization.


This article is from the "Rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1917520

Part.6 of the Face object of 8.python (supplementary authorization and inheritance concept)

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.