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
- Object created
- Object is quoted
- Object is used as an argument to a function or method
- Object is treated as an element in a container
Causes a reference to -1 The situation is all 4 Kind of
- Object deleted
- The name of the object, give a new object
- Object out of scope
- 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
The sidebar is recommended
- Some people say Python does not support function overloading?
- "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system with Python
- Introduction to Python - CONDA common commands
- Python actual combat | just "4 steps" to get started with web crawler (with benefits)
- Don't know what to eat every day? Python to tell you! Generate recipes and don't worry about what to eat every day!
- Are people who like drinking tea successful? I use Python to make a tea guide! Do you like it?
- I took 100g pictures offline overnight with Python just to prevent the website from disappearing
- Binary operation of Python OpenCV image re learning and image smoothing (convolution processing)
- Analysis of Python event mechanism
- Iterator of Python basic language
guess what you like
-
Base64 encryption and decryption in Python
-
Chapter 2: Fundamentals of python-2 variable
-
Python garbage collection summary
-
Python game development, pyGame module, python takes you to realize a magic tower game from scratch (1)
-
Python draws a spinning windmill with turtle
-
Deep understanding of Python features
-
A website full of temptations for Python crawler writers, "lovely picture network", look at the name of this website
-
Python opencv Canny edge detection knowledge supplement
-
Complex learning of Python opencv Sobel operator, ScHARR operator and Laplacian operator
-
Python: faker extension package
Random recommended
- Python code reading (Part 44): find the location of qualified elements
- Elegant implementation of Django model field encryption
- 40 Python entry applet
- Pandas comprehensive application
- Chapter 2: Fundamentals of python-3 character string
- Python pyplot draws a parallel histogram, and the x-axis value is displayed in the center of the two histograms
- [Python crawler] detailed explanation of selenium from introduction to actual combat [1]
- Curl to Python self use version
- Python visualization - 3D drawing solutions pyecharts, Matplotlib, openpyxl
- Use python, opencv's meanshift and CAMSHIFT algorithms to find and track objects in video
- Using python, opencv obtains and changes pixels, modifies image channels, and trims ROI
- [Python data collection] university ranking data collection
- [Python data collection] stock information collection
- Python game development, pyGame module, python takes you to realize a magic tower game from scratch (2)
- Python solves the problem of suspending execution after clicking the mouse in CMD window (fast editing mode is prohibited)
- [Python from introduction to mastery] (II) how to run Python? What are the good development tools (pycharm)
- Python type hints from introduction to practice
- Python notes (IX): basic operation of dictionary
- Python notes (8): basic operations of collections
- Python notes (VII): definition and use of tuples
- Python notes (6): definition and use of lists
- Python notes (V): string operation
- Python notes (IV): use of functions and modules
- Python notes (3): conditional statements and circular statements
- Python notes (II): lexical structure
- Notes on python (I): getting to know Python
- [Python data structure series] - tree and binary tree - basic knowledge - knowledge point explanation + code implementation
- [Python daily homework] Day7: how to combine two dictionaries in an expression?
- How to implement a custom list or dictionary in Python
- 15 advanced Python tips for experienced programmers
- Python string method tutorial - how to use the find() and replace() functions on Python strings
- Python computer network basics
- Python crawler series: crawling global airport information
- Python crawler series: crawling global port information
- How to calculate unique values using pandas groupby
- Application of built-in distribution of Monte Carlo simulation SciPy with Python
- Gradient lifting method and its implementation in Python
- Pandas: how to group and calculate by index
- Can you create an empty pandas data frame and fill it in?
- Python basic exercises teaching! can't? (practice makes perfect)