current position:Home>Python notes (11): encapsulation such as object-oriented programming
Python notes (11): encapsulation such as object-oriented programming
2022-01-30 12:38:32 【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 ~
The understanding of encapsulation
encapsulation (Encapsulation): Abstraction of properties and methods
-
Attribute abstraction : The properties of the class ( Variable ) Define 、 Isolation and protection
It is divided into private attributes and public attributes
- Private property : Can only be accessed inside a class
- Public attributes : You can use the 、 Object name access
You can choose to expose or hide properties , The internal mechanism of hiding attributes
-
Abstraction of methods : Methods for classes ( function ) Define 、 Isolation and protection
It is divided into private methods and public methods
- Private method : Can only be accessed inside a class
- Open methods : You can use the 、 Object name access
You can choose to expose or hide the method , Hide the internal logic of the method
-
The goal is to form an interface for externally operable properties and methods
Encapsulation is the process of making data and code called classes , Expressed as : class —— attribute —— Method
Private class properties 、 Expose class properties 、 Private instance properties and public instance properties
Expose class properties
Public class attributes are class attributes , Grammatical structure
class ClassName:
< Class property name > = < Class attribute initial value >
def __init__(self,[ Parameters 1], [ Parameters 2], ...[ Parameters n]):
self.< Instance property name > = < Initial value of instance attribute >
...
Copy code
Private class properties
Private class properties can only be accessed by the current class , Subclass cannot access . Grammatical structure
class ClassName:
<__ Private class property name > = < Initial value of property >
def __init__(self,[ Parameters 1], [ Parameters 2], ...[ Parameters n]):
self.< Instance property name > = < Initial value of instance attribute >
...
Copy code
.< Class properties >
perhaps < Object name >.< Class properties >
Mode of access
Effectively ensure the controllability of attribute maintenance
The sample code is as follows :
class TestClass:
__number = 0
def __init__(self, num_value):
for i in range(num_value + 1):
TestClass.__number += i
@classmethod # Class method
def sum_number(cls):
return TestClass.__number
value1 = TestClass(100)
print(TestClass.sum_number()) # 5050
# print(value1.__number) # AttributeError: 'TestClass' object has no attribute '__number'
Copy code
In class takeout visit .__number
Will report AttributeError
abnormal
Expose instance properties
Exposing the instance property is equal to the instance property , Grammatical structure
class < Class name >:
< Class property name > = < Class method value >
def __init__(self, < parameter list >):
self.< Instance property name > = < Instance property value >
...
Copy code
Private instance properties
Private instance properties can only be used inside the current class , Subclasses cannot use . Grammatical structure
class < Class name >:
< Class property name > = < Class method value >
def __init__(self, < parameter list >):
self.<__ Private instance property name > = < Instance property value >
...
Copy code
.< Class properties >
perhaps < Object name >.< Class properties >
Mode of access
Effectively ensure the controllability of attribute maintenance
Sample code
class TestClass:
def __init__(self, num_value):
self.__number = 0
for i in range(num_value + 1):
self.__number += i
def sum_number(self):
return self.__number
value1 = TestClass(100)
print(value1.sum_number()) # 5050
# print(value1.__number) # AttributeError: 'TestClass' object has no attribute '__number'
Copy code
Private attributes are not necessarily really private
The double underline of private attributes is just a conversion Convention , After the transformation , The original name in the class has changed , This is a formal private
Sample code
class TestClass:
def __init__(self, num_value):
self.__number = 0
for i in range(num_value + 1):
self.__number += i
def sum_number(self):
return self.__number
value1 = TestClass(100)
print(value1.sum_number()) # 5050
print(value1._TestClass__number) # 5050
# Can pass Object name ._ Class name __ attribute The way to access
Copy code
Can pass Object name ._ Class name __ attribute
The way to access .
Private methods and public methods
Defining a method is a method defined and used inside a class . Grammatical structure
class < Class name >:
def <__ Private method name >(self, < parameter list >):
...
Copy code
When defining a private method, two underscores are required in front of the attribute name (__
).
All kinds of methods can change the method into private method by adding double down line change
Private methods formally protect Python The function logic used inside the class
Private attributes and disclosure are programmer logic , Not security logic , Pay attention to the agreement
Reserved properties of class
Python Class properties reserved by the interpreter , Start or end with double down lines .
- Reserved attributes are also called special attributes
- Start and end with a double underscore
- The function is to understand Python Class provides a unified attribute interface
- Attribute values have special meanings , Use directly after class definition
Just use < Class name >
Access reserved properties
Keep attributes | describe |
---|---|
__name__ |
Noun of class |
__qualname__ |
With . Separate class names starting from the template global namespace |
__bases__ |
The name of the base class inherited by the class |
Class's reserved methods
The retention method is Python Method reserved by interpreter , Start and end with a double underscore
- The retention method is also called special method
- Start and end with a double underscore
- The function is to understand Python Class provides a unified method interface
- Method logic : It has a specific meaning , Generally associated with operators , Class definitions need to be overloaded
copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301238288443.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)