current position:Home>Python notes (14): advanced technologies such as object-oriented programming

Python notes (14): advanced technologies such as object-oriented programming

2022-01-30 12:38:16 A bowl week

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~

Concept of reference

quote (Reference) Is a pointer to an object

  • A reference is a pointer to a real object in memory , Expressed as variable name or memory address
  • Each object has at least one reference ,id() Function to get a reference
  • When passing parameters and assignments ,Python Pass a reference to the object , Instead of copying objects

Sample code

list1 = [1, 2, 3, 4]
list2 = list1
print(id(list1))  # 2044656837192
print(id(list2))  # 2044656837192
#  because list1 Is an instantiation of a class ,list2 The reference is list1, Both are the most basic of references object class , So the results of the two are the same 
 Copy code 

Python The internal mechanism handles references

  • Immutable object :immutable The interpreter maintains as few memory areas as possible for the same value
  • The variable object :mutable The interpreter maintains different memory areas for each object

Sample code 1

text1 = " A bowl week "
text2 = text1
text3 = " A bowl week "
text4 = " A bowl "
text5 = " Zhou "
text6 = text4 + text5
print(id(text1))  # 1616972638288
print(id(text2))  # 1616972638288
print(id(text3))  # 1616972638288
print(id(text4))  # 1616973621272
print(id(text5))  # 1616973578032
print(id(text6))  # 1616974246288
 Copy code 

because text1 and 2 Is a string of references , So the memory address is the same ; because Python The interpreter will save memory space as much as possible , So when the values of immutable types are the same ,Python It will automatically reference an address space , To save space , therefore text1/2/3 The address space is consistent ;Python The interpreter does not optimize the address space of the calculated results , Even if the two values are the same ,Python The interpreter will also open up a new address space for the newly calculated result

Sample code 2

list1 = []
list2 = []
list3 = []
print(id(list1))  # 3204114440776
print(id(list2))  # 3204114440840
print(id(list3))  # 3204115873544
 Copy code 

Each mutable object has its own independent address space , Do not reuse address space

Cause the reference to be +1 In general 4 Kind of

  1. Object created
  2. Object is quoted
  3. Object is used as an argument to a function or method
  4. Object is treated as an element in a container

Causes a reference to -1 The situation is all 4 Kind of

  1. Object deleted
  2. The name of the object, give a new object
  3. Object out of scope
  4. The container of the object is deleted

Copy of object

Copy is to copy an object as a new object , Memory space has ” change “, Copy is divided into shallow copy and deep copy

  • Shallow copy : Copy only the copy method of the topmost object , Default copy method
  • Deep copy : Copy all objects iteratively

Sample code ( Shallow copy 1)

list1 = [" Sweet ", [1, 2, 3]]
list2 = list1.copy()  #  Use copy Method copy 
list3 = list1[:]  #  Use slice to copy 
list4 = list(list1)  #  Use the generated list method to copy 
for ch in [list1, list2, list3, list4]:
    for i in ch:
        print(i, id(i),  "\t", end="")  #  Print the list without any items and id
    print(ch, id(ch))  #  Print each list and id
    
'''
--- Output results ---
 A bowl week  2905817180184   [1, 2, 3] 2905787490888   [' A bowl week ', [1, 2, 3]] 2905787490952
 A bowl week  2905817180184   [1, 2, 3] 2905787490888   [' A bowl week ', [1, 2, 3]] 2905817092488
 A bowl week  2905817180184   [1, 2, 3] 2905787490888   [' A bowl week ', [1, 2, 3]] 2905817137800
 A bowl week  2905817180184   [1, 2, 3] 2905787490888   [' A bowl week ', [1, 2, 3]] 2905817771656
'''
 Copy code 

Shallow copy is just the memory space of the list of copies , The memory space of the elements inside will not be copied

Sample code ( Shallow copy 2)

list1 = [" A bowl week ", [1, 2, 3]]
list2 = list1.copy()  #  Use copy Method copy 
list3 = list1[:]  #  Use slice to copy 
list4 = list(list1)  #  Use the generated list method to copy 
list4[1].append(4)
print(list1)
print(list2)
print(list3)
print(list4)
'''
-- Output results --
[' A bowl week ', [1, 2, 3, 4]]
[' A bowl week ', [1, 2, 3, 4]]
[' A bowl week ', [1, 2, 3, 4]]
[' A bowl week ', [1, 2, 3, 4]]
'''
 Copy code 

Here only for list4 To modify the data , But the contents of all the lists have changed ; This is because the content referenced by each list is the same , So I modified 1 Four will change

The deep copy shall adopt copy In the library deepcopy() Method , Iteratively copy the objects of all levels within the object , Completely open up new memory space, establish objects and various object elements under objects , Deep copy is only for variable categories , Immutable types are not allowed to create new objects

Sample code

import copy  #  Import library 
list1 = [" A bowl week ", [1, 2, 3]]
list2 = copy.deepcopy(list1)  #  Use copy Library deepcopy Method copy 
for ch in [list1, list2]:
    for i in ch:
        print(i, id(i),  "\t", end="")  #  Print the list without any items and id
    print(ch, id(ch))  #  Print each list and id

'''
--- Output results ---
 A bowl week  2190823984184   [1, 2, 3] 2190853845832   [' A bowl week ', [1, 2, 3]] 2190853766728
 A bowl week  2190823984184   [1, 2, 3] 2190853961544   [' A bowl week ', [1, 2, 3]] 2190853961480
'''
 Copy code 

because “ Sweet ” String is of immutable type , So its address space will not change , The rest of the address space has changed

Reference to instance method

Instance method is also a reference , Is a reference to the object itself , When a method is referenced , Method ( It's a function ) Will produce an object : Method object

Class's feature decorator

@property The decorator can change the method to be visible ” attribute “, Inside the class, it is represented as a method , On the outside, it appears as an attribute

Sample code

class TestClass:
    def __init__(self, name):
        self.name = name

    @property    #  Convert methods to properties 
    def age(self):
        return self.__age

    @age.setter  #  Assign values to attributes 
    def age(self, value):
        if value < 0 or value > 110:
            value = 19
        self.__age = value


tt = TestClass(" A bowl week ")
bb = TestClass(" A cup of porridge ")
tt.age = 18
bb.age = -19
print(tt.age)  # 18
print(bb.age)  # 19
 Copy code 

The name of the class modifies

Name modification (Name Mangling) Is the name conversion convention in the class ,Python Some important functions can be accomplished through name modification , stay Python Underline... In _ To decorate the name , It is divided into 5 In this case ,

  • _name
  • name_
  • __name
  • __name__
  • _

_ Names beginning with a single underscore decorate

  • A property or method starting with a single underscore is a convention used inside a class , yes PEP8 A prescribed agreement
  • It's just an agreement , Still pass < Object name >.< Property name > Access to
  • The difference in function is the use of from XX import * Properties or methods starting with a single underscore will not be imported

Sample code

class TestClass:
    def __init__(self, name):
        self._name = name  #  Agreed to be used internally 


tt = TestClass(" A bowl week ")
print(tt._name)  #  A bowl week 
 Copy code 

Although the agreement is used internally , But it can still be accessed

_ Names ending with a single underscore decorate

The property or method of ending with a single underscore is to avoid conflicts with reserved words or existing names , This is also PEP8 Stipulated , It's just a convention , There is no corresponding function

__ Names that begin with a double underscore decorate

The double underscore property or method will be changed by the interpreter , Avoid naming conflicts , This is not an agreement , It's functional ,__nama Will be changed to _< Class name >__name In the form of , To implement private properties 、 Private method ; This is a kind of name modification , Indirectly as private properties or private methods

__name__ Double underlined names at the beginning and end decorate

Properties or methods that begin and end with double underscores have no special functions , The name cannot be changed , Part of the name is reserved property or reserved method

Underline

Is a single underline just an insignificant name , No special functions

Python Minimum empty class of

effect

  • Class is a namespace , The smallest empty class can be used as a namespace

    • The smallest empty class can assist in storage and use
    • Dynamically adding attributes is Python A feature of class

Sample code

class TestClass:
    pass


a = TestClass
a.text = " A bowl week "
print(a.text)  #  A bowl week 
#  You can dynamically add attributes to achieve the purpose of storing information 
 Copy code 

copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301238125817.html

Random recommended