current position:Home>Python notes (12): inheritance such as object-oriented programming
Python notes (12): inheritance such as object-oriented programming
2022-01-30 12:38:22 【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 ~
Understanding of inheritance
Inherit (Inheritance) : High level abstraction of code reuse
- Inheritance is one of the essence of object-oriented design
- It realizes the high-level abstract code reuse based on classes
- Inheritance is a process in which a newly defined class can almost completely use the properties and methods of the original class
Whether it's a base class or a derived class , It's just an inheritance statement , These are all ordinary Python class
You can also press subclasses 、 Parent class and superclass Division .
The most basic class is the base class , After one inheritance, the derived class , You can also inherit again , Another derived class ; Now the most basic class and the derived class inherited for the first time are the relationship between parent and child classes , Derived class the last derived class is also the relationship between parent class and child class , The most basic class and the last derived class belong to the relationship between superclass and subclass
A derived class can not only inherit a base class , You can also inherit multiple base classes , This is the concept of multi inheritance
Construction of class inheritance
When a class inherits, the inheritance relationship is declared at the time of definition , The syntax is as follows
class < Derived class name >(< Base class name >): # The base class name can take the path :ModuleNama.BaseClassName
def __init__(self, < parameter list >):
< Sentence block >
...
Copy code
Derived classes can directly use the properties and methods of the base class
- The properties of the base class are basically equal to those defined in the derived class
- Derived classes can directly use the class properties of the base class 、 Instance attributes
- Derived classes can directly use various methods of the base class
- When using class methods and class properties of a base class , To call... With the class name of the base class
The sample code
class TestClass:
def __init__(self, number):
self.sum_number = 0
for i in range(number + 1):
self.sum_number += i
def sum_num(self):
return self.sum_number
class HumanNameClass(TestClass):
def double_sum(self):
return self.sum_number * 2 # Use of base class properties
value1 = HumanNameClass(100)
print(value1.sum_num()) # 5050 # Use of base class instance methods
print(value1.double_sum()) # 10100 # Use of derived class instance methods
Copy code
Python There are two functions related to the judgment of inheritance relationship
function | describe |
---|---|
isinstance(object, classinfo) |
Judge the object object Whether it is classinfo Instance or subclass instance of , return True perhaps False |
issubclass(class, classinfo) |
Judgment parameters class Whether it is a type parameter classinfo Subclasses of , return True perhaps False. |
Follow the code above ,
print(isinstance(value1, TestClass)) # True
print(isinstance(value1, HumanNameClass)) # True
print(isinstance(value1, int)) # False
print(issubclass(HumanNameClass, TestClass)) # True
print(issubclass(TestClass, HumanNameClass)) # False
Copy code
Python The most basic class in
because Python Everything is an object , Any class is also an object 、Python All data types are also objects ;Python The most basic class of all classes provided by the language is object.
- object yes Python The most basic noun , There is no need to translate
- All definitions inherit by default object
- Reserved attributes and reserved methods are essentially object Class properties and methods
Sample code
print(object.__name__) # Print object Name # object
print(object.__bases__) # Print object Inherited class name # ()
print(object.__doc__) # Print object Class description # The most base type
print(object.__module__) # Print object Name of the module # builtins
print(object.__class__) # object Corresponding class information # <class 'type'>
Copy code
Python The three elements of the object
- identification identity: Once the object is built, it will not change , use
id()
get , Usually memory address - type type: Type of object , use
type()
get - value value: Divided into variable mutable And immutable immutable Two kinds of
Two related to basic classes Python The built-in function
function / keyword | describe |
---|---|
id(x) | return x The logo of .CPython in id() Function to get the memory address of an object . |
x is y |
Judge x and y Whether the identifications of are equal , return True or False, No judgment value |
Python Class overload
Overloading is the definition of a derived class to a base class property or method
- Property Override : The derived class defines and uses an attribute with the same name as the base class
- Method overloading : The derived class defines and uses a method with the same name as the base class
Property Override
Attribute overloading adopts the principle of nearby coverage , Overloading requires no special marking . Methods and steps
- Give priority to the redefined properties and methods of derived classes
- Then find the properties and methods of the base class
- Looking for super class properties and methods
The sample code
class TestClass:
text = " This is the class attribute of the base class "
def __init__(self, number):
self.sum_number = 0
for i in range(number + 1):
self.sum_number += i
def sum_num(self):
return self.sum_number
class HumanNameClass(TestClass):
text = " This is the class attribute of the derived class " # Class attribute overload
def __init__(self, number):
self.sum_number = 1000 # Instance property overload
def double_sum(self):
return self.sum_number * 2
value1 = HumanNameClass(100)
print(TestClass.text) # This is the class attribute of the base class
print(value1.text) # This is the class attribute of the derived class
print(value1.sum_num()) # 1000
Copy code
Method overloading
Method overloading is the definition of a derived class to a base class method ; It is divided into full overload and incremental overload
Full reload : Derived classes completely redefine methods with the same name as the base class
Directly define the method with the same name in the derived class
Sample code
class TestClass:
def __init__(self, number):
self.sum_number = 0
for i in range(number + 1):
self.sum_number += i
def sum_num(self):
return self.sum_number
class HumanNameClass(TestClass):
def sum_num(self): # Reconstruction of methods
return self.sum_number * 2
value1 = HumanNameClass(100)
print(value1.sum_num()) # 10100
Copy code
Incremental reload : Derived class extensions define methods with the same name as the base class , Grammatical structure
class < Derived class name >(< Base class name >):
def < Method name >(self, < parameter list >):
super().< Base class method name >(< parameter list >)
...
Copy code
Incremental overloading uses
super()
function
Sample code
class TestClass:
def test_text(self):
print(" This is the method of the base class ")
class TestClass1(TestClass):
def test_text(self): # Incremental reload
super().test_text()
print(" This is the statement in the new method ")
doc1 = TestClass()
doc2 = TestClass1()
print(doc1.test_text())
print(doc2.test_text())
'''
--- Output results ---
This is the method of the base class
None # Because the function does not return a value
This is the method of the base class
This is the statement in the new method
None # Because the function does not return a value
'''
Copy code
Multiple inheritance of classes
The construction of multiple inheritance is to declare the inheritance relationship at the time of definition , Grammatical structure
class < Class name >(< Base class name 1>, < Base class name 2>,..., < Base class name N>): # The base class name can take the path :ModuleNama.BaseClassName
def __init__(self, < parameter list >):
< Sentence block >
...
Copy code
Python Depth first is adopted in multi inheritance , From left to right . The so-called depth first, from left to right, is to start from the leftmost , Find his base class , If the base class is not looking up , Until the most basic object Class has not been found yet , Just started looking to the right .
All properties and methods are used according to “ Depth priority from left to right ” Method selection
Constructors also refer to the above principles ,super()
Also refer to the above principles
The order of multiple base classes is the key
Sample code
class Test1:
def test(self):
text = " This is the base class 1"
return text
class Test2:
def test(self):
text = " This is the base class 2"
return text
class Test3(Test1, Test2):
pass
class Test4(Test2, Test1):
pass
value1 = Test3()
value2 = Test4()
print(value1.test()) # This is the base class 1
print(value2.test()) # This is the base class 2
Copy code
Determine the output in sequence
Understanding of the concept of inheritance , Construction of class inheritance , I understand object yes Python The most basic class in
The overloading principle of class attributes is the nearest coverage principle
Overloading of class methods : Reloading is similar to reloading class attributes ; Incremental overloading uses super()
function
The method of multi inheritance is depth first , From left to right
copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301238187039.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)