Analysis of Python object-oriented programming

Overview

Many people come into contact with Python, starting with crawlers. In fact, many languages can be used as crawlers, but Python is simpler than other languages. But Python is not limited to crawlers, it is more widely used in artificial intelligence and scientific computing. The ancients said: If you want to make great progress, it is important to lay a good foundation. This article mainly explains the object-oriented knowledge of Python, which is only for learning and sharing. If you have any shortcomings, please correct me.

Object-oriented features

Class: A collection of characteristics used to describe the same thing, such as the Person class, which represents a person and has human attributes and characteristics.
Object: A concrete instance defined by a class, such as: zhangsan represents a concrete person.
Inheritance: assigns a class to inherit the methods and properties of the base class, and has its own properties and characteristics, such as: Man is a subclass of Person.
Encapsulation: hide data and implementation details, and provide external access methods.
Polymorphism: A base class can have multiple derived classes and can have different forms.
Abstraction: The process of setting aside details and focusing only on essential features.
The above are the basic features of object-oriented, so how does Python do in object-oriented?

Create class

As follows:

classEmployee:"""Staff category"""
 emp_count =0 #Variable is a class variable, its value will be shared among all instances of this class

 def __init__(self, name, salary):"""initialization"""
 self.name = name
 self.salary = salary
 Employee.emp_count +=1

 def display_count(self):"""Display quantity"""print('Total Employee =', Employee.emp_count)

 def display_employee(self):"""Display information"""print('name =', self.name,', salary = ', self.salary)

 def prt(self):"""Print yourself"""print(self)print(self.__class__)

 def __del__(self):"""Destructor"""print(self,'Was released')

Create object

Python creates objects without the new keyword, which is similar to function calls, which is different from Java and .Net. As follows:

' Create the first object'
 emp =Employee('Jack',20)
 emp.display_count()
 emp.display_employee()
 emp.prt()

Dynamically add and delete object properties

Object attributes can be added dynamically, which is different from compiled languages, as shown below:

 emp.age =17 #add one'age'Attributes
 emp.age =28 #modify'age'Attributes
 del emp.age #delete'age'Attributes

You can also add and get attributes through Python's built-in methods, as shown below:

print(getattr(emp,'name')) #Get attributes
print(hasattr(emp,'age')) #Whether to include attributes
setattr(emp,'age',18) #Set attributes and values
print(hasattr(emp,'age')) #Whether to include attributes
print(getattr(emp,'age')) #Get attributes
delattr(emp,'age') #Delete attribute
print(hasattr(emp,'age')) #Whether to include attributes

Python also has some attributes of built-in classes, as shown below:

 # Built-in objects
 print("Employee.__doc__:", Employee.__doc__)print("Employee.__name__:", Employee.__name__)print("Employee.__module__:", Employee.__module__)print("Employee.__bases__:", Employee.__bases__)print("Employee.__dict__:", Employee.__dict__)

Class attributes and methods

As follows:

classJustCounter:"""Class description"""
 __ secretCount =0 #Class private variables
 publicCount =0 #Public variable

 def count(self):
 self.__secretCount +=1
 self.publicCount +=1print('Private variables:', self.__secretCount)

Python does not allow instantiated classes to access private data, but you can use object._className__attrName (object name._class name__private attribute name) to access attributes, as shown below:

print(counter._JustCounter__secretCount)

Class inheritance

One of the main benefits of object-oriented programming is code reuse. One of the ways to achieve this reuse is through inheritance. The new class created through inheritance is called a subclass or derived class, and the inherited class is called a base class, a parent class, or a super class.

As shown below: Parent represents a parent class with its own properties and methods.

classParent:"""Define the parent class"""
 parentAttr =100

 def __init__(self):print('Call the constructor of the parent class')

 def parentMethod(self):print('Call parent method')

 def setAttr(self, attr):
 Parent.parentAttr = attr

 def getAttr(self):print('Parent attribute:', Parent.parentAttr)

 def myMethod(self):print('I am the MyMethod of the parent class')

Child represents a subclass, inherited from Parent, as follows:

classChild(Parent):"""Define subclass"""

 def __init__(self):print('Call the subclass's constructor')

 def childMethod(self):print('Call subclass method')

 def myMethod(self):"""Override the Overrides parent class method"""print('I am a subclass of MyMethod')

 def __str__(self):"""Rewrite method, suitable for human reading"""return'str method returns'

Instantiation of subclasses

As follows:

 c =Child() #Instantiate subclass objects
 c.childMethod() #Call subclass method
 c.parentMethod() #Call parent method
 c.setAttr(200) #Call the parent method again to set the properties
 c.getAttr() #Call the parent class method again to get the attributes
 c.myMethod() #The MyMethod of the subclass is called

The relationship between subclasses and classes can be judged through built-in functions, as shown below:

print(issubclass(Child, Parent)) #Determine whether it is the corresponding parent-child relationship
 print(isinstance(c, Child)) #Determine whether it is an instance object
 print(isinstance(c, Parent)) #Determine whether it is an instance object

Recommended Posts

Analysis of Python object-oriented programming
Analysis of common methods of Python multi-process programming
Python analysis of wav files
Analysis of JS of Python crawler
Analysis of usage examples of Python yield
Analysis of Python conditional control statements
​Full analysis of Python module knowledge
How to understand python object-oriented programming
Basic analysis of Python turtle library implementation
7 features of Python3.9
Detailed analysis of Python garbage collection mechanism
Python network programming
Python object-oriented example
Python data analysis
Python object-oriented basics
Method analysis of Python calling C language program
Python implementation of AI automatic matting example analysis
Python object-oriented magic method
12. Network Programming in Python3
Detailed Python IO programming
Python linear interpolation analysis
Basics of Python syntax
Basic syntax of Python
Basic knowledge of Python (1)
Prettytable module of python
09. Common modules of Python3
Consolidate the foundation of Python (4)
In-depth understanding of python list (LIST)
Talking about Python functional programming
Consolidate the foundation of Python(6)
Python3 crawler data cleaning analysis
python king of glory wallpaper
Python programming Pycharm fast learning
Consolidate the foundation of Python(5)
Python3 script programming commonly used.md
Python implementation of gomoku program
Deep understanding of Python multithreading
XTU programming Python training three
Black Hat Programming Application Python2
Python version of OpenCV installation
What is object-oriented in python
Python Data Science: Related Analysis
9 feature engineering techniques of Python
matplotlib of python drawing module
Python method of parameter passing
Consolidate the foundation of Python (3)
Collection of Python Common Modules
Python crawler advanced essential | Decryption logic analysis of an index analysis platform
The usage of wheel in python
Summary of logarithm method in Python
Detailed explanation of python backtracking template
Analysis of Hyper-V installation CentOS 8 problem
Detailed implementation of Python plug-in mechanism
Detailed explanation of python sequence types
Implementation of reverse traversal of python list
Python implementation of IOU calculation case
Magic methods and uses of Python
In-depth understanding of Python variable scope
Python preliminary implementation of word2vec operation
FM algorithm analysis and Python implementation
Python handles the 4 wheels of Chinese