Advanced Python object oriented programming and the like
- 2021-12-11 18:37:16
- OfStack
1. The concept of reference
Reference (
Reference
) is a pointer to an object
A reference is a pointer to a real object in memory, expressed as a variable name or memory address
There are at least 1 reference per object,
id()
Function is used to get a reference
When passing parameters and assigning values,
Python
Pass a reference to an object instead of copying it
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 of which are the most basic references object Class, so the result of the two is 1 Like
Python
Handling of references by internal mechanisms
immutable
The interpreter maintains as little memory area as possible for the same value
Variable object:
mutable
The interpreter maintains a different memory area for each object
Sample code:
text1 = "1 Bowl week "
text2 = text1
text3 = "1 Bowl week "
text4 = "1 Bowl "
text5 = " Week "
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
Because
text1
And 2 are 1 string referenced, so the memory address is 1-like; Because
Python
The interpreter will save memory space greatly, so when the value of immutable type is 1, Python will automatically refer to 1 address space to save space, so
text1/2/3
The address space of is 1; The Python interpreter does not optimize the address space of the calculated results, even if the values of the two are one,
Python
The interpreter will also open up a new address space for the newly calculated results
Sample code:
list1 = []
list2 = []
list3 = []
print(id(list1)) # 3204114440776
print(id(list2)) # 3204114440840
print(id(list3)) # 3204115873544
Each mutable object has its own independent address space and does not reuse the address space
There are 4 cases 1 that cause the reference to be +1
Object is created Object is referenced Object is used as an argument to a function or method Object is treated as an element in 1 containerThere are also 4 kinds of situations that lead to citation-1
Object is deleted The name of the object is given to the new object Object out of scope The container in which the object is located is deleted
2. Copy of object
Copy is to copy an object as a new object, and the memory space has "changes". Copy is divided into shallow copy and deep copy
Shallow copy: Copy only the top-level object, the default copy method Deep copy: Copy method of iteratively copying all objectsSample Code (Shallow Copy 1)
list1 = [" Sweet ", [1, 2, 3]]
list2 = list1.copy() # Use copy Method replication
list3 = list1[:] # Copy with slices
list4 = list(list1) # Copy using build list
for ch in [list1, list2, list3, list4]:
for i in ch:
print(i, id(i), "\t", end="") # Print the list without 1 Items and id
print(ch, id(ch)) # Print each list and id
'''
--- Output result ---
1 Bowl week 2905817180184 [1, 2, 3] 2905787490888 ['1 Bowl week ', [1, 2, 3]] 2905787490952
1 Bowl week 2905817180184 [1, 2, 3] 2905787490888 ['1 Bowl week ', [1, 2, 3]] 2905817092488
1 Bowl week 2905817180184 [1, 2, 3] 2905787490888 ['1 Bowl week ', [1, 2, 3]] 2905817137800
1 Bowl week 2905817180184 [1, 2, 3] 2905787490888 ['1 Bowl week ', [1, 2, 3]] 2905817771656
'''
Shallow copy only copies the list of memory space of this layer 1, and the memory space of the elements inside will not be copied
Sample Code (Shallow Copy 2)
list1 = ["1 Bowl week ", [1, 2, 3]]
list2 = list1.copy() # Use copy Method replication
list3 = list1[:] # Copy with slices
list4 = list(list1) # Copy using build list
list4[1].append(4)
print(list1)
print(list2)
print(list3)
print(list4)
'''
-- Output result --
['1 Bowl week ', [1, 2, 3, 4]]
['1 Bowl week ', [1, 2, 3, 4]]
['1 Bowl week ', [1, 2, 3, 4]]
['1 Bowl week ', [1, 2, 3, 4]]
'''
It's only right here
id()
0
The data was modified, but all the contents of the list happened; This is because the contents referenced by each list are 1, so if you modify 1 and 4, it will change
Deep copy should be used
copy
Inside the library
deepcopy()
Method, iteratively copying each level of objects in the inner layer of the object, completely opening up new memory space to establish objects and various object elements in the lower layer of the object, deep copying only for variable categories, and no new objects are allowed to be created for immutable types
Sample code
import copy # Import library
list1 = ["1 Bowl week ", [1, 2, 3]]
list2 = copy.deepcopy(list1) # Use copy Library deepcopy Method replication
for ch in [list1, list2]:
for i in ch:
print(i, id(i), "\t", end="") # Print the list without 1 Items and id
print(ch, id(ch)) # Print each list and id
'''
--- Output result ---
1 Bowl week 2190823984184 [1, 2, 3] 2190853845832 ['1 Bowl week ', [1, 2, 3]] 2190853766728
1 Bowl week 2190823984184 [1, 2, 3] 2190853961544 ['1 Bowl week ', [1, 2, 3]] 2190853961480
'''
Because the "sweet" string is an immutable type, its address space does not change, and the rest of the address space has changed
2.1 References to Instance Methods
An instance method is also a kind of reference, that is, a reference to the object itself. When a method is referenced, the method (that is, a function) will produce an object: a method object
Feature decorators of class 2.2
@property
The decorator can change a method into an externally visible "property", which is represented as a method inside the class and a property outside the class
Sample code
class TestClass:
def __init__(self, name):
self.name = name
@property # Convert a method to a property
def age(self):
return self.__age
@age.setter # Assign a value to a property
def age(self, value):
if value < 0 or value > 110:
value = 19
self.__age = value
tt = TestClass("1 Bowl week ")
bb = TestClass("1 Bowl of porridge ")
tt.age = 18
bb.age = -19
print(tt.age) # 18
print(bb.age) # 19
3. Class name modification
Name modification (
Name Mangling
) is the conversion convention for names in a class,
Python
You can accomplish some important functions through name modification, in
Python
Use the underscore _ to decorate the name, which can be divided into five situations.
_name
name_
__name
__name__
_
3.1 _ Name modification beginning with single underscore
A single-underlined property or method is a convention used inside the class, which isPEP8
A prescribed agreement
It's just an agreement, it can still be passed
<
Object name
>
.
<
Attribute name
>
Mode access
The difference in function is the use of
from XX import
* does not import properties or methods that begin with a single underscore
Sample code
class TestClass:
def __init__(self, name):
self._name = name # Contracts are used internally
tt = TestClass("1 Bowl week ")
print(tt._name) # 1 Bowl week
Although the contract is used internally, it can still be accessed
3.2 _ Single underlined ending name modification
A single-underlined ending property or method is to avoid conflicts with reserved words or existing names, which is also
PEP8
As stipulated, this is only a convention without any corresponding function
3.3 __ Double-underlined name modification
A double-underlined property or method will be named by the interpreter to avoid naming conflicts, which is not a convention but functional,
_nama
Will be modified to _
<
Class name
>__name
To realize private attributes and private methods; This is the name modification of class 1, which is indirectly used as a private property or a private method
3.4 __name__ Double Underscore Beginning and Ending Name Modification
Double-underlined beginning and ending properties or methods have no special features, their names cannot be modified, and some of their names are reserved properties or reserved methods
3.5 Single Underline
Is a single underline just an insignificant name, no special function
4. The smallest empty class of Python
Function:
Class is a namespace, and the smallest empty class can be used as a namespace
The smallest empty class can assist in storage and use The dynamically added attribute isPython
One characteristic of class
Sample code:
class TestClass:
pass
a = TestClass
a.text = "1 Bowl week "
print(a.text) # 1 Bowl week
# Attributes can be dynamically added to achieve the purpose of storing information