current position：Home>Object oriented and exception handling in Python
Object oriented and exception handling in Python
2022-02-01 00:03:02 【Non serious programmer】
This is my participation 11 The fourth of the yuegengwen challenge 19 God , Check out the activity details ：2021 One last more challenge
As we have said before Python There are several main object types built in ,（ Count , character string , list , Tuples and dictionaries ）. And the core character of object-oriented has not appeared yet . So what kind of objects do we often say , In fact, his type is “ class ”. Inheritance encapsulation and polymorphism , This is the general idea of object-oriented programming .
Python Inheritance in
Inheritance is to improve the reusability of code , Subclasses can implement the methods in the parent class by inheriting the parent class , This is just being lazy . give an example ：
class Person(): def eat(self): print("person can eat ...") def slepp(self): print("person can slepp ...") calss Man(Person): def hardWork(self): print("man should be work hard ...") # test m = Man() m.eat() # person can eat ... Copy code
The above example , It shows a lot of problems , First , Defining a class is to use
class keyword , Define method usage
def, A parameter is passed in by default , In fact, this parameter does not have to be called
self But for identification , We define , Because it represents the current object , similar Java Medium this . Of course, our inheritance is through a bracket + Defined by parent class , What then? Person I didn't write , In fact, one is omitted here
object If you don't write it, it means default inheritance
object Superclass . in addition ,Python Support for multiple inheritance , Just like this ,
calss Man(Animal,Person) A problem needs attention , When multiple superclasses contain the same method , Whichever is in the following parent class shall prevail . however , Multiple inheritance is not recommended .
Python Package in
encapsulation , It's easy to understand , Is to hide the attribute information in the class , Provide public methods for calling , We'll do the attribute ” Privatization “, Precede the attribute with two underscores
__name Define a fake private property . Look at examples ：
class Man(): def __init(self): # This is the initialization method of the object , Creating objects is the default execution self.__name = '' def set_name(self,name): self.__name = name def get_name(self): return self.__name m = Man() # Create objects m.set_name('YJK923') # Set up name value ( It's actually _Man__name ) m.get_name() # obtain name value ( It's actually _Man__name ) 'YJK923' m.name = 'YJK' # Note that there is another attribute added here name m.get_name() # obtain name value ( It's actually _Man__name ) 'YJK923' m.name # Get just for m Created name Value 'YJK' m._Man__name # get attribute _Man__name , This is it. Python A greasy place , In fact, there is no privatization , Just convert the format . 'YJK923' Copy code
Python The polymorphic
And polymorphism , Simple understanding , There are many states , The common method is the same method, but the execution effect is different , It's like there are too many people with the same name , And everyone is different , See? , Programming ideas also come from daily life . give an example , All sleep , But some people like to lie in bed , Some people like to sleep in chairs . How to implement it in code ？ Look below
class People(): def sleep(self): print(" People sleep ...") class Roommate(People): def sleep(self): print(' Sleep in a chair ...') Copy code
See? , Also sleep ,Roommate But sleeping in a chair , Realizing polymorphism through inheritance is just a way to realize polymorphism . There are other ways , Like this , The parameters of the method are superclasses .
# Different objects call the same method , The result is the same . fun(obj): print( obj.__len__() ) Copy code
Python The method commonly used in
Add a few examples of common methods
# Standard module random Contains a name called choice Function of , Used to select an element from the sequence . from random import choice x = choice(['Hello,world !',[1,2,'e','e',4]]) x.count('e') 2 # Randomly generated , Maybe not 2 # Judgement class A Is it right? B Subclasses of issubclass(A,B) # My son is in front of me , I'm in the back # Find the class A All the superclasses of A.__bases__ # Find an object A All properties in A.__dict__ # Look for objects A Which class does it belong to A.__class__ # Check whether the method or property exists in the object hasattr(instance,'methedName | attrName') # Set the properties of the object setattr(instance,'attrName',value') Copy code
Python Abstract classes in
About abstract classes ： Defines a rule （ Abstract method ）, Subclasses that inherit this class must implement the abstract methods in the abstract class . and , Abstract classes cannot be instantiated .
Python Introduced in
abc Module to implement the definition of abstract classes , Example ：
# The following representation defines a abstract class Talker , Contains an abstract method talk . from abc import ABC,abstractmethod class Talker(ABC): @abstractmethod def talk(self): pass Copy code
Insert a song about some thoughts on object-oriented design .
- Put things together , If a method wants to use global variables , Then take it as the attribute and method of the class
- Don't let objects get too close . This is the so-called decoupling and .
- Careful inheritance , Especially multiple inheritance .
- Keep it simple , Make the method as short and concise as possible .
How to translate requirements into concrete entity classes ？ We can try that . Describe the requirements and record the nouns in them , Verbs and adjectives . Find the possible class in the noun , Find out the possible way in the verbs , Find possible attributes in adjectives , Finally, assign the found methods and attributes to each class . The model of this class comes out , Then we can think about the relationship between objects , Inherit or combine . Later, we'll think about the modes that can be used for the corresponding business , After each business module has thought clearly, you can start programming . Copy code
Python The exception handling mechanism in
Let's talk about it briefly Python The exception handling mechanism in .
Throw an exception and use the keyword
raise for example ,
raise Exception('exception msg !') However, it should be noted that the exception thrown can only be Exception or Exception Subclasses of .
Capture exception ： We can use
try ... except : ... finally: ... Statement block to handle code that may have exceptions .
try 1 / 0 except ZeroDivisionError as e: print(e) else : print('No exception will run ...') finally : print('must be run ... ') Copy code
Custom exception classes , Define a class inheritance Exception The class can .
class MyException(Exception): pass Copy code
author[Non serious programmer],Please bring the original link to reprint, thank you.
The sidebar is recommended
- leetcode 1560. Most Visited Sector in a Circular Track（python）
- leetcode 1995. Count Special Quadruplets（python）
- How to program based on interfaces using Python
- leetcode 1286. Iterator for Combination（python）
- leetcode 1418. Display Table of Food Orders in a Restaurant （python）
- Python Matplotlib drawing histogram
- Python development foundation summary (VII) database + FTP + character coding + source code security
- Python modular package management and import mechanism
- Django serialization (II)
- Python dataloader error "dataloader worker (PID XXX) is killed by signal" solution
guess what you like
apache2. 4 + Django + windows 10 Automated Deployment
leetcode 1222. Queens That Can Attack the King（python）
leetcode 1387. Sort Integers by The Power Value （python）
Tiger sniffing 24-hour praise device, a case with a crawler skill, python crawler lesson 7-9
Python object oriented programming 01: introduction classes and objects
Baidu Post: high definition Python
Python Matplotlib drawing contour map
Python crawler actual combat, requests module, python realizes IMDB movie top data visualization
Python classic: explain programming and development from simple to deep and step by step
Python implements URL availability monitoring and instant push
- Python avatar animation, come and generate your own animation avatar
- leetcode 1884. Egg Drop With 2 Eggs and N Floors（python）
- leetcode 1910. Remove All Occurrences of a Substring（python）
- Python and binary
- First acquaintance with Python class
- [Python data collection] scrapy book acquisition and coding analysis
- Python crawler from introduction to mastery (IV) extracting information from web pages
- Python crawler from entry to mastery (III) implementation of simple crawler
- The apscheduler module in Python implements scheduled tasks
- 1379. Find the same node in the cloned binary tree (Java / C + + / Python)
- Python connects redis, singleton and thread pool, and resolves problems encountered
- Python from 0 to 1 (day 11) - Python data application 1
- Python bisect module
- Python + OpenGL realizes real-time interactive writing on blocks with B-spline curves
- Use the properties of Python VTK implicit functions to select and cut data
- Learn these 10000 passages and become a humorous person in the IT workplace. Python crawler lessons 8-9
- leetcode 986. Interval List Intersections（python）
- leetcode 1860. Incremental Memory Leak（python）
- How to teach yourself Python? How long will it take?
- Python Matplotlib drawing pie chart
- Django paging (II)
- Concurrent. For Python concurrent programming Futures or multiprocessing?
- Programmers over the age of 25 can't know a few Chinese herbal medicines. Python crawler lessons 9-9
- Python crawler from introduction to pit full series of tutorials (detailed tutorial + various practical combat)
- The second bullet of class in Python
- Python object oriented programming 03: class inheritance and its derived terms
- How IOS developers learn Python Programming 13 - function 4
- Python crawler from introduction to mastery (VI) form and crawler login
- Python crawler from entry to mastery (V) challenges of dynamic web pages
- Deeply understand pandas to read excel, TXT, CSV files and other commands
- Daily python, Chapter 18, class
- "I just want to collect some plain photos in Python for machine learning," he said. "I believe you a ghost!"
- Django view
- Python implements filtering emoticons in text
- When winter comes, python chooses a coat with temperament for mom! Otherwise, there's really no way to start!
- Python crawler - get fund change information
- Highlight actor using Python VTK
- Python crawler actual combat: crawling southern weekend news articles
- leetcode 406. Queue Reconstruction by Height（python）
- leetcode 1043. Partition Array for Maximum Sum （python）