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