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()
# 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' = 'YJK' # Note that there is another attribute added here  name
m.get_name() #  obtain  name  value  (  It's actually  _Man__name )
'YJK923' #  Get just for  m  Created  name  Value 
m._Man__name #  get attribute  _Man__name , This is it.  Python  A greasy place , In fact, there is no privatization , Just convert the format  .
 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  .
    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]])
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 

#  Find an object  A  All properties in 

#  Look for objects  A  Which class does it belong to 

#  Check whether the method or property exists in the object 
hasattr(instance,'methedName | attrName')

#  Set the properties of the object 
 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):
    def talk(self):
 Copy code 

Insert a song about some thoughts on object-oriented design .

  1. Put things together , If a method wants to use global variables , Then take it as the attribute and method of the class
  2. Don't let objects get too close . This is the so-called decoupling and .
  3. Careful inheritance , Especially multiple inheritance .
  4. 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 .

    1 / 0
except ZeroDivisionError as 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):
 Copy code 

copyright notice
author[Non serious programmer],Please bring the original link to reprint, thank you.

Random recommended