Python Learn to Organize

Source: Internet
Author: User
Tags shallow copy

-Our normal replication is the deep copy, which will be copied completely again as a separate new individual exists. Therefore, changing the original copied object will not affect the new object that has been copied.
-Shallow copy does not produce a separate object, he simply hits the original block with a new tag , so when one of the tags is changed, the data block changes and the other tag changes. This is different from what we have in the ordinary sense of replication.

For simple object, it's no different with shallow copy and deep copy

Complex object, such as the list in the case, shallow copy of the sub-list, not from the original object really "independent" out. In other words, if you change an element in the child list of the original object, your copy will change along with it. This is different from our intuitive understanding of "copy".

Python stores variables in a different way than other OOP languages. instead of assigning a value to a variable, it is a reference to a specific value.

When in Python a = something should be understood to put a label on the something. When you assign a value to a, it's like taking a tag off the original something and pasting it onto other objects to create a new reference.

copy is not completely copied for a complex object's child objects , what is a child object of a complex object? Like nested sequences in a sequence, nested sequences in a dictionary are sub-objects of complex objects. For sub-objects, Python stores it as a public image, and all copies of it are treated as a reference, so that when one of the references changes the mirror and the other reference uses the mirror, the image is changed.

Deepcopy will copy each layer of the complex object to a single individual.

Contextual Manager (context Manager)/with keyword

When writing code, we want to put some action into a block of code so that it can be kept in a certain state of operation when executed in a block of code, while another operation is performed when the block is left, and the current state is ended , so simply, the purpose of the context manager is to specify the scope of the object. Take "process" if it goes out of scope.

First, let's take a look at the code that doesn't use the context manager, and see what happens when it runs.

 #   hl.txt  , "  w   " )  #   run here, it will print false because it is not closed  f.write ( hello,context manager!   " ) F.close ()  print  (f.closed) #   This prints true to show file close  

If this code does not execute at all f.close () This sentence, is not a problem, if we are in the process of writing, the disk is full, the code will be written in the sentence of the exception, so that will never execute f.close () This sentence, the file will never be closed, Perhaps you would say that I can use the try...finally statement ah, do not solve the problem, but there will be problems in it.
The problem is that when we do not simply write, but other more complex operations, such as copying, while reading and writing, you will see that the try...finally statement simply does not guarantee the beauty of the code, it is simply too bad. So, the context manager comes in handy, and it guarantees that your code is beautiful and secure whenever you like.

When the context manager is used:

# When using the context managerwith open("hl.txt","w" ) as F:    print(f.closed)  #False    f.write ("  Hello,context manager! " )print(f.closed)  #True no need to perform f.close ()

The WITH keyword is always accompanied by the context manager, and the AS keyword assigns open ("Hl.txt", "w") to the new object F, making it possible to perform arbitrary operations on F in the code block, which is fairly concise.

Custom Context Manager

To be a context manager, you need to do something that requires two methods:_enter_() and _exit_();
_enter_ (): Responsible for entering the code block preparation work, before the call;
_exit_ (): Responsible for leaving the code block after the aftermath of the work, left after being called;

Therefore, a Python class can be said to be a context manager as long as it implements both of the above methods.

classFileRead (object):def __init__(self,filename,read_method='W'): Self.obj=file (Filename,read_method)def __enter__():       returnSelf.objdef __exit__(): Self.obj.close () with FileRead ('Test.txt') as F:f.write ('s')

Yield keyword

For iteration

A brief analysis of Python yield usage

Fibonacci sequence

def Fab (max):      = 0, 0, 1 while      n < Max:         yield  b         #        A, B = B, A + b         

Call:

 for  in Fab (5): ...      Print

Simply put, the function of yield is to turn a function into a generator, the function with yield is no longer a normal function, the Python interpreter treats it as a generator, and the Call to FAB (5) does not execute the FAB function, but instead returns a Iterab Le Object! When the For loop executes, each loop executes the code inside the Fab function, and when it executes to yield B, the FAB function returns an iteration value , and the next iteration, the code proceeds from the next statement of Yield B, and the local variable of the function looks and ends before the last interrupt execution. All the same, the function continues until the yield is encountered again.

You can also call the next () Method of Fab (5) Manually (because Fab (5) is a generator object that has the next () method)

>>> f = Fab (5>>>1 >>>1 >>>2 >>>  3 >>>5 >>> f.next () Traceback (most recent):  "< stdin>" in <module> stopiteration

When the function execution finishes, generator automatically throws the Stopiteration exception, indicating that the iteration is complete. In the For loop, there is no need to handle the stopiteration exception and the loop will end normally.

We can draw the following conclusions:

A function with yield is a generator, which, unlike a normal function, generates a generator that looks like a function call, but does not execute any function code until it calls next () (which is automatically called next () in the For loop) to begin execution. Although the execution process still executes according to the process of the function, each execution to a yield statement is interrupted and an iteration value is returned, and the next execution proceeds from the next statement of yield. It looks as if a function was interrupted several times by yield during normal execution, and each break returns the current iteration value through yield.

The benefits of yield are obvious, and the ability to rewrite a function into a generator yields an iterative capability that computes the value of the next next () rather than the instance of the class, not only the code is concise, but the execution process is exceptionally clear.

In Python 3.x, next () should be replaced with __next__ ()

Python Learn to Organize

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.