Python object-oriented 5 basics, python object-oriented

Source: Internet
Author: User

Python object-oriented 5 basics, python object-oriented

Python object-oriented 5 Basics

Today, the remaining object-oriented knowledge will be learned mainly in the following aspects: 1. Context Management Protocol; 2. Adding a class modifier; 3. Meta-class

I. Context Management Protocol

When learning file operations, the operations on a file are as follows:

With open ('filename ', 'Mode') as f: 'Code Block'

The above is called the context management protocol, that is, the with statement. To make an object compatible with the with statement, the _ enter _ and _ exit _ methods must be declared in the class of this object.

Class Foo: def _ init _ (self, name): self. name = name def _ enter _ (self): print ('execute enter') return self def _ exit _ (self, exc_type, exc_val, exc_tb ): print ('execute exit ') print (exc_type) print (exc_val) print (exc_tb) return Truewith Foo('a.txt') as f: # f is an instantiated object of Foo, (You can think of it as f = Open('a.txt) # execute with Foo('a.txt ') as f will trigger the _ enter _ method in the Foo class. This method passes self as the return value to f # After the code in the with code block is executed, the _ exit _ method will be triggered. print (f) # <__ main __. foo object at 0x01EC2070> print (asdfsaasdfasdfasdfasdfasfasdfasdfasdfasdfasdfasfdasfd) # If an exception occurs in the code block # The _ exit _ method is directly triggered, and an error is reported in the code block, if there is a return value in the _ exit _ method, the error message is swallowed up, print (f. name) print ('-----------------') print ('---------------') print ('alipay') print ('-----------------') print ('-----------------') print ('20140901') # Run the _ exit _ method first and then execute this sentence.

Purpose or benefit:

1. The purpose of using the with statement is to put the code block into the with for execution. After the with statement is completed, the cleaning is automatically completed without manual intervention.

2. in programming environments that require resource management, such as files, network connections, and locks, you can customize the automatic resource release mechanism in _ exit _. You do not have to worry about this issue any more, this will be of great use

2. Load the decorator for the class

I learned about the decorator when I was learning functions. Now I am still talking about the object-oriented decorator. Is it so fun to install the decorator in classes? First, we must first understand that classes and functions are both objects and so. Then let's take a look at the symbol @ of the decorator, what do you mean by adding a modifier to a class?

# @ Name ----> the meaning is that it does not care about the content and treats them as objects. # eg: @ echo: the execution of this sentence is equivalent to: teacher = echo (teacher) # def teacher () # @ echo: Student = echo (Student) # calss Student ()

Here is an example of a function:

Def decho (func): print ('==============') return func @ decho # execute this row equivalent to ==> test = decho (test) def test (): print ('.............. ') test ..............

Here is an object-oriented example:

Def test (obj): print ('=>', obj) obj. name = 'Alex 'obj. age = 45 obj. gender = 'male' return obj @ test # is equivalent to executing Foo = test (Foo) class Foo (): passprint (Foo. _ dict _) print (Foo. name) the output result is: <class '_ main __. foo '> {' _ module _ ':' _ main _ ',' _ dict __': <attribute '_ dict _' of 'foo' objects>, '_ weakref _': <attribute '_ weakref _' of 'foo' objects>, '_ doc _': None, 'name': 'Alex ', 'age': 45, 'gender': 'male'} alex

Finally, let's write an example of a modifier with parameters:

Def MO (** kwargs): def test (obj): print ('---->', obj) for k, v in kwargs. items (): setattr (obj, k, v) return obj print ('=>', kwargs) #==========================>{ 'name': 'Alex ', 'age': 45, 'gender ': 'male'} return test @ MO (name = 'Alex ', age = 45, gender = 'male') class Teacher (): print (' ___> ') passprint (Teacher. _ dict _) @ MO (name = 'houliangong') class Studet (): print ('wangbada') print (Studet. _ dict _) the output result is: ====================>{ 'name': 'Alex ', 'age': 45, 'gender': 'male'} ___> ----> <class '_ main __. teacher '> {' _ module _ ':' _ main _ ',' _ dict __': <attribute '_ dict _' of 'teacher' objects>, '_ weakref _': <attribute '_ weakref _' of 'teacher' objects>, '_ doc _': None, 'name': 'Alex ', 'age': 45, 'gender ': 'male' }==============================>{ 'name ': 'houangong'} wangbadan ----> <class '_ main __. studet '> {' _ module _ ':' _ main _ ',' _ dict __': <attribute '_ dict _' of 'studet' objects>, '_ weakref _': <attribute '_ weakref _' of 'studet' objects>, '_ doc _': None, 'name': 'houliangong '}

Iii. Metadata

What is a Meta class? Meta-class refers to the class. It is a template for creating a class. You can use it to create a class. so, do you have to learn if it is so powerful.

Meta-classes are used to control how to create classes, just as classes are templates for object creation.

The metadata instance is a class, just as the class instance is an object (f1The object is an instance of the Foo class.,The Foo class is an instance of the type class)

Type is an internal Meta class of python, which is used to directly control the generation class. Any class defined in python is actually an object of type class instantiation.

Create two metadatabase modes:

Method 1:

1 class Foo:2     def func(self):3         print('from func')

Method 2:

1 def func (self): 2 print ('from func') 3 x = 14 Foo = type ('foo', (object,), {'func': func, 'X': 1}) # When type is used to create a class, you must enter the first class name to be created for the three parameters. The second parameter is represented by a tuples for the class, the third parameter is represented by the dictionary type for the passed data attribute.

A class does not declare its own Meta class. By default, its Meta class is type, except for the use of Meta class type, you can also customize the metadatabase by inheriting the type (by the way, we can also take a look at how the metadatabase controls the creation of the class and what is the workflow)

Well, we can customize a metadata class:

Class Mytype (type): def _ init _ (self, class_name, bases = None, dict = None): print ("Mytype init --->") print (class_name, type (class_name) print (bases) print (dict) def _ call _ (self, * args, ** kwargs): print ('mytype call ----> ', self, args, kwargs) obj = self. _ new _ (self) self. _ init _ (obj, * args, ** kwargs) return objclass Foo (object, metaclass = Mytype ): # in python3 #__ metaclass _ = MyType # in python2 x = 1111111111 def _ init _ (self, name): self. name = name def _ new _ (cls, * args, ** kwargs): return super (). _ new _ (cls) # return object. _ new _ (cls) # Same as f1 = Foo ('name') print (f1. _ dict __)

I wrote it here today. It's a little tired!

 

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.