Python in-depth copy garbage collection and super Inheritance (vi)

Source: Internet
Author: User
Tags shallow copy

1 python copy

Deep copy, shallow copy and reference three differences

ImportCopya=[1,2,3,4, [' A ',' B ']]#原始对象B=A#赋值, a reference to a passing objectC=Copy.copy (a)#对象拷贝, Shallow copyD=Copy.deepcopy (a)#对象拷贝, deep copyA.append (5)#修改对象aa[4].append (' C ')#修改对象a中的 [' A ', ' B '] Array objectPrint(' A = 'APrint(' B = ', b)Print(' C = 'CPrint(' d = ', d) Output result: a=[1,2,3,4, [' A ',' B ',' C '],5]#a执行两次值追加操作B=[1,2,3,4, [' A ',' B ',' C '],5]#赋值是对象的引用, B-point is still a, so it's consistent with a contentC=[1,2,3,4, [' A ',' B ',' C ']]#对象的浅拷贝外部list重新生成新的空间, but the memory address of the nested arrays does not changeD=[1,2,3,4, [' A ',' B ']]#深拷贝是所有的数组都新生成一个内存空间, with the original separation of the relationship
2 Python garbage collection mechanism

Python GC uses reference counts (reference counting) primarily to track and recycle garbage. On the basis of reference counting, through "mark-clear" (Mark and sweep) to solve the problem that the container object may produce circular reference, through "generational recovery" (generation collection) to improve garbage collection efficiency by means of space-time-changing.

1 Reference count

? Pyobject are the necessary content for each object, which ob_refcnt is the reference count. When an object has a new reference, it is ob_refcnt incremented, and when the object referencing it is deleted, it is ob_refcnt reduced. The object's life ends when the reference count is 0 o'clock.

Advantages:

    1. Simple
    2. Real-time sex

Disadvantages:

    1. Maintain reference count consumption resources
    2. Circular references
2 Mark-Clear mechanism

The basic idea is to allocate on demand, wait until there is no free memory from the register and the reference on the stack to start, traverse the object as a node, the reference as the edge of the graph, all the objects can be accessed to mark, and then sweep the memory space, all unmarked objects released.

3 Generational Technology

The whole idea of generational recycling is that all memory blocks in the system are divided into different sets according to their survival time, each set becomes a "generation", and the garbage collection frequency decreases with the increase of the survival time of "generation", and the survival time is usually measured by several garbage collection.

Python By default defines a collection of three generations of objects, the larger the number of indexes, the longer the object survives.

Example:
When some memory blocks M has survived after 3 garbage collection cleaning, we row the memory block m into a set a, and the newly allocated memory is divided into set B. When garbage collection begins to work, most cases are garbage collected only for collection B, and collection A is garbage collected for quite a long time, which makes the garbage collection mechanism need to deal with less memory, the efficiency naturally increased. In this process, some blocks of memory in set B are transferred to set a because of their long lifetime, and of course there is some garbage in the collection A, which is delayed because of this generational mechanism.

3 is and = = var and let in Python

is to compare the memory address = = of the two is a basic comparison of the two values

is判定    =10=10is bTure    常用的1-256计算机共用一个内存地址        =9999999=9999999is bFalse    数值较大的数类似长整型,计算机会生成新的内存地址var与let    var 定义的变量可以重新被定义    let 定义的变量不能重新被定义
4 python in read ReadLine readlines

Read () reads the entire file every time, and it is typically used to put the contents of a file into a string variable

ReadLine reads the next line, uses the generator method, returns the object of the string

ReadLines reads the entire file into an iterator for us to traverse

#readF= Open("A.txt") lines=F.read ()Print(lines)Print(type(lines)) F.close ()#输出# Hello# python!<type ' str '> #字符串类型#readlineF= Open("A.txt") Line=F.readline ()Print(type(line)) whileLinePrintLine, line=F.readline () F.close ()#输出#<type ' str ' ><type ' str '> #字符串类型# Hello# python!#readlinesF= Open("A.txt") lines=F.readlines ()Print(type(lines)) forLineinchLinesPrint(line) F.close ()#输出<type ' list '> # Hello# python!
5 The difference between Python2 and Python3
Contents Python3 Description
Print function Python3 Printing with parentheses
Divisible /can get floating point number
Unicode Unicode (utf-8)String
Xrange Module Use range uniformly, and add__contains__
Raising exceptions/handling Exceptions Raise and AS Keywords
Next () function Keep only next() , .next() throw property exceptions
For loop forLoop variables no longer cause namespace leaks
Compare non-sortable types Python does not support different types of comparisons
Enter input Only input is allowed and Raw_input is canceled.
6 Python must learn super

(1) Super () Inheritance method

In the inheritance of a class, if you redefine a method that overrides a method of the same name in the parent class, but sometimes we want to be able to implement the function of the parent class at the same time, we need to invoke the parent class's method, which can be used super to implement the

classAnimal (Object):#Animal为父类    def __init__( Self, name): Self. Name=NamedefGreet Self):Print ' Hello, I am%s. ' %  Self. NameclassDog (Animal):#Dog为子类    defGreet Self):#Dog重定义了greet方法并继承了父类的方法        Super(Dog, Self). Greet ()# Python3 can use Super (). Greet ()        Print ' Wangwang ... '        >>>Dog=Dog (' dog ')#实例化>>>Dog.greet ()#调用greet方法Hello, I am dog. Wangwang.

(2) Super initialization

superOne of the most common usages of calling a parent class in a subclass is to initialize the method

class Base(object):    def__init__(self, a, b):        self= a        self=class A(Base):    def__init__(self, a, b, c):        superself).__init__(a, b)  # 初始化子类继承父类super(子类名,self).__init__(父类参数)        self= c    

Python3 can be used as super().__init__(a, b) a class that inherits the properties of the parent class while maintaining its own unique properties.

(3) in-depth super

Super doesn't actually have a real relationship with the parent class.

classBase (Object):def __init__( Self):Print "Enter Base"        Print "Leave Base"  classA (Base):#继承base    def __init__( Self):Print "Enter A"        SuperA Self).__init__()Print "Leave A" classB (Base):#继承base    def __init__( Self):Print "Enter B"        SuperB Self).__init__()Print "Leave B" classC (A, B):#多重继承自A, B    def __init__( Self):Print "Enter C"        SuperC Self).__init__()#super第一个参数可以是继承链中任意类名字        Print "Leave C"        #输出>>>C=C () Enter Center aenter benter baseleave baseleave bleave aleave C

As we understand, enter a below the output should be base class base in the Enter base, why is enter B?? The reason is that super is not associated with the parent class, so the order of execution is a-->b-->base

The execution process is:

When you initialize C (), you first call the constructor of a super(A, self).__init__() , super(A, self) return the Class B after a in the inheritance order of the current class, and then execute it in such a way that the order is super(B,self).__init()__ executed.

The Super method can see that the first parameter ofsuper () can be the name of any class in the inheritance chain.

1 if it is in itself, it will inherit the next class sequentially;

2 if the previous class in the inheritance chain will be infinitely recursive;

3 If the class is in the inheritance chain, the class between the inheritance chain summary itself and the passed-in class is ignored;

Python in-depth copy garbage collection and super Inheritance (vi)

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.