Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze python exception handling and object-oriented programming

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how to carry out python exception handling and object-oriented programming analysis, the editor feels very practical, so share with you to learn, I hope you can learn something after reading this article, say no more, follow the editor to have a look.

Exception handling and object-oriented programming are important foundations of python programming. In the actual production programming design and development, exception handling and image-oriented must be fully considered in the process of design and development.

For the foundation of python development and object-oriented, a python program is used to encapsulate the two parts, and the results are as follows:

#! / usr/bin/env python

# _ * _ coding:utf-8 _ * _

#

# exception handling

#

Print''

Exception handling is a mechanism used to deal with abnormal conditions in software or information systems, and some special conditions that exceed the normal execution process of the program.

In the current error handling mechanism of mainstream programming languages, exception handling gradually replaces error code error handling, and exception handling separates receiving and handling error codes.

This feature clarifies programming ideas and enhances the readability of the code, making it easy for maintainers to read and understand.

''

Print

Print''

Exception handling, known as error handling, provides a method for any unexpected or abnormal conditions that occur while the program is running.

Python exception handling uses keywords such as try,catch,else,finally to try operations that may not succeed, handle failures and normal situations, and clean up resources afterwards.

The syntax for catching and handling python exceptions is as follows:

# blocks where exceptions may occur

Try:

Block_try

# the first except form

Except Exception1:

Block_when_exception1_happen

# second form of except

Except (Exception2, Exception3, Exception4):

Block_when_exception2_or_3_or_4_happen

# the third form of except

Except Exception5, variance

Block_when_exception5_happen

# the fourth form of except

Except (Exception6, Exception7), variance

Block_when_exception6_or_7_happen

# the fifth form of except

Except:

Blok_for_all_other_exceptions

# handling when no exception occurs

Else:

Block_for_no_exceptions

# the last thing to do, regardless of whether there is an exception or not

Finally:

Block_anyway

''

Print

Print''

Exception handling rules are divided into four parts:

The code that may produce an exception is written in the try block. If an exception occurs in the try block, the remaining code in the try block is terminated.

The code for exception judgment and occurrence, written in except, has five forms:

1 is that when an exception occurs, execute the code within the except block; 2) catch a variety of exceptions and execute the code; 3) that the caught exception can be converted into a variable; 4) catch a variety of exceptions into variables; 5) catch any exception

Each form of except capture can be defined multiple times, and the system will check one by one, but when one condition is met, the except block is executed, and the others are no longer checked and executed, similar to multiple if-else conditions.

Else is an optional module that defines what to do if no exception occurs

Finally is an optional module, and the code here will be executed regardless of whether the try module has an exception or not

To sum up, the try module is the program object, except is the exception capture submission and response, else is the handling when there is no exception, and finally is the last thing that must be executed, regardless of whether an exception occurs.

''

Print

# simple exception handling example

Try:

Result = 3AGO

Print "This is never been called"

Except:

Print "Exception happened"

Finally:

Print "Process finished!"

# examples of multiple except exception capture modules

Try:

MyList = [4,6]

Print myList [10]

Print "This is never been called"

Except ZeroDivisionError, e:

Print "ZeroDivisionError happened"

Print e

Except (IndexError, EOFError), e:

Print "Exception happened"

Print e

Except:

Print "Unkown exception happened"

Else:

Print "No exception happened!"

Finally:

Print "Process finished!"

Print

Print''

In addition to system predefined exceptions, you can also define your own specific logical exceptions.

Define the exception yourself, create a subclass that inherits the system exception, and throw the exception with the raise statement when it needs to be thrown.

''

# Custom exception example

Import sys

Class MyError (Exception):

Def _ str__ (self):

Return "I am a self-defined Error!"

Def main_except ():

Try:

Print "* Start of main () *"

If len (sys.argv) = = 1:

Raise MyError ()

Print "* End of main () *"

Except MyError, e:

Print e

Main_except ()

#

# object-oriented programming

#

Print

Print''

Image-oriented programming, compared with process-oriented programming, functional programming is characterized by:

Process-oriented: write base code from top to bottom according to business logic

Functional: encapsulate a functional code into a function, so that you don't need to write it repeatedly in the future, just call the function.

Object-oriented: classify and encapsulate functions to make the development "faster, better and stronger."

Object-oriented programming is a kind of programming, which needs to be realized by using "class" and "object". Therefore, object-oriented programming is actually the use of "class" and "object".

A class is a template, which can contain multiple functions and implement some functions.

The object is the instance created according to the template, through which the function in the class can be executed.

The three characteristics of object-oriented are encapsulation, inheritance and polymorphism.

''

Print

Print''

Object-oriented is not only a standard of program design, but also a method of program development. Python can support both functional programming and object-oriented programming. Object-oriented programming can realize the function of functional programming, but functional programming is not necessarily.

Generally can use object-oriented programming, try to use object-oriented programming to achieve. Some advanced functions, such as C # and Java, only support object-oriented programming, not functional programming.

Object-oriented, an object refers to an instance of a class, a class is a template for creating objects, a class can create multiple objects, each object is a variable of the class type; the process of creating an object is also called class instantiation.

The main concepts in object-oriented programming are:

Class class: defines the abstraction of a thing. A class defines the properties of things and the behavior it can do. there can be member functions and member variables in a class. In image-oriented reading, member functions are called methods and member variables are called attributes.

Object object: is an instance of a class, and each class can have several instantiated objects. In OS, the bear allocates memory to the image, not to the class

Inheriting inheritance: refers to defining another class (subclass) through an existing class (parent class), which shares properties and methods open to the parent class. Whether the object of a subclass is an instance of a subclass or an instance of a parent class.

Encapsulation encapsulation: encapsulation means that when defining, you can define the members that can not or do not need to be known by other classes as private members, and only disclose the members that need to be used, so as to achieve the role of information hiding and simplification.

Polymorphic polymorphism: it means that the same method acts on different readings and can have different interpretations, resulting in different execution results. In implementation, polymorphism means that the maternal developer sets the variable of the parent object to a reference to the child object. After the assignment, the parent object variable can operate in different ways according to the characteristics of the current assignment to the child object.

With the popularity of object-oriented programming OOP, object-oriented related to OOD is also gradually mature, forming a standard modeling language represented by UML.

UML is a graphical language that supports modeling and software system development. It provides modeling and visualization support for all stages of software development, from requirements analysis to specifications to construction and configuration.

''

Print

Print "classes and readings are the basis of object-oriented programming. Class variables can be instantiated directly by adding parentheses after the class name, and member functions and member variables can be accessed using object variables. there can be no return value in the constructor."

# define a class

Class MyClass (object):

Message = "Hello, Developer."

Def show (self):

Print self.message

Print MyClass.message

MyClass.message = "Good Morning!"

Print MyClass.message

Inst = MyClass ()

Inst.show ()

Print

Print "constructor is a special class member method, which is mainly used to initialize objects and assign initial values to object members when creating objects. In python, the constructor is named with _ _ init__, adding a constructor to the class and instantiating an object."

# define classes and add constructor examples

Class MyClass (object):

Message = 'Hello, Developer.'

Def show (self):

Print self.message

Def _ init__ (self):

Print "Constructor is called"

Inst = MyClass ()

Inst.show ()

# use default parameters to construct objects in multiple ways

Class MyClass (object):

Message = "Hello, Developer."

Def show (self):

Print self.message

Def _ _ init__ (self, name = "unset", color = "black"):

Print "Constructor is called with params:", name, "", color

Inst = MyClass ()

Inst.show ()

Inst2 = MyClass ("David")

Inst2.show ()

Inst3 = MyClass ("Lisa", "Yellow")

Inst3.show ()

Inst4 = MyClass (color = "Green")

Inst4.show ()

Print

Print''

The destructor, which is the reverse function of the constructor, calls the destructor when the released object is destroyed. Destructors often do clean-up work, such as database connections, and can use destructors to determine whether they take up database resources.

The way in python to define a destructor for a class is to define a _ _ del__ function in the class that does not return values and parameters.

Similar to Java, the python interpreter stores the object created by the running program lock in the heap without formal release; if you need to display the destroyed object, use the del keyword.

''

# create class and call destructor example

Class MyClass (object):

Message = 'Hello, Developer.'

Def show (self):

Print self.message

Def _ _ init__ (self, name = 'unset', color = "black"):

Print "Constructor is called with params:", name, "", color

Def _ del__ (self):

Print "Destructor is called!"

Inst = MyClass ()

Inst.show ()

Inst2 = MyClass ("David")

Inst2.show ()

Del inst, inst2

Inst3 = MyClass ("Lisa", "Yellow")

Inst3.show ()

Del inst3

Print

There are shared member variables in the print "class, such as message in the above class. If you want to define each object's own member variable, define the variable referenced by self in the constructor, that is, the instance member variable."

# example of instance member variables

Class MyClass (object):

Message = "Hello, Developer."

Def show (self):

Print self.message

Print "Here is s in s!" (self.name, self.color)

Def _ _ init__ (self, name = "unset", color = "black"):

Print "Constructor is called with params:", name, "", color

Self.name = name

Self.color = color

Def _ del__ (self):

Print "Destructor is called for s!" self.name

Inst2 = MyClass ("David")

Inst2.show ()

Print "Color of inst2 is", inst2.color, "\ n"

Inst3 = MyClass ("Lisa", "Yellow")

Inst3.show ()

Print "Name of inst3 is", inst3.name, "\ n"

Del inst2, inst3

Print''

When you access a class, the class member function is bound to the instance and can only be accessed through the object, not through the class name.

Python supports two functions that access members based on class names: static functions and class functions. The difference between them is that the class function has an invisible parameter cls that can be used to obtain class information, while the static function does not change the parameter.

Static functions are defined using decorator @ staticmethod, and class functions are defined using decorator @ classmethod.

''

# Code examples of static and class functions

Class MyClass (object):

Message = "Hello, Developer."

Def show (self):

Print self.message

Print "Here is s in s!" (self.name, self.color)

@ staticmethod

Def printMessage ():

Print "print Message is called"

Print MyClass.message

@ classmethod

Def createObj (cls, name, color):

Print "Object will be created:% s (% s,% s)"% (cls.__name__, name, color)

Return cls (name, color)

Def _ _ init__ (self, name = "unset", color = "black"):

Print "Constructor is called with params:", name, "", color

Self.name = name

Self.color = color

Def _ del__ (self):

Print "Destructor is called for s!" self.name

MyClass.printMessage ()

Inst = MyClass.createObj ("Toby", "Red")

Print inst.message

Del inst

Print

Print''

Encapsulation is an important feature of image-oriented programming, and python also provides a private member mechanism that prevents the outside world from seeing members singing.

But unlike the way most programming languages express visible ranges with the public,private keyword, python defines private members in the format of variable names, and members that start with a double underscore _ _ are member variables.

''

# Encapsulation, sample code for private members

Class MyClass (object):

Def _ _ init__ (self, name = "unset", color = "black"):

Print "Constructor is called with params:", name, "", color

Self.__name = name

Self.__color = color

Def _ del__ (self):

Print "Destructor is called for s!" self.__name

Inst = MyClass ("Jojo", "White")

Del inst

Print''

Inheritance, inheritance between classes is an important method of object-oriented design, through inheritance can simplify code and optimize design patterns.

When the python class is defined, you can specify the base class in parentheses. All python classes are subclasses of the object type. The syntax is as follows:

Class BaseClass (object): # parent class definition

Block_class

Class SubClass (BaseClass): # subclass definition

Block_class

In addition to having its own features defined in block_class, subclasses inherit non-private features from the parent class.

It is a good way to call the destructor of the base class in the destructor of the subclass, but this may cause the parent class resources to not be released as scheduled.

''

# inheritance, subclass inheritance parent class example

Class Base (object):

Def _ init__ (self):

Print "Constructor fo Base is called!"

Def _ del__ (self):

Print "Destructor of Base is called!"

Def move (self):

Print "move called in Base!"

Class SubA (Base):

Def _ init__ (self):

Print "Constructor of subA is called!"

Def move (self):

Print "move called in subA!"

Class SubB (Base):

Def _ del__ (self):

Print "Destructor of SubB is called!"

Super (SubB, self). _ _ del__ ()

InstA = SubA ()

InstA.move ()

Del instA

Print "- -"

InstB = SubB ()

InstB.move ()

Del instB

Print

Print "python allows multiple inheritance of classes, that is, a subclass can have multiple base classes."

# one subclass, inheriting multiple parent class examples

Class BaseA (object):

Def move (self):

Print "move called in BaseA!"

Class BaseB (object):

Def move (self):

Print "move called in BaseB!"

Class BaseC (BaseA):

Def move (self):

Print "move called in BaseC!"

Class Sub (BaseC, BaseB):

Pass

Inst = Sub ()

Inst.move ()

The execution result of the script is as follows:

# python try.py

Exception handling is a mechanism used to deal with abnormal conditions in software or information systems, and some special conditions that exceed the normal execution process of the program.

In the current error handling mechanism of mainstream programming languages, exception handling gradually replaces error code error handling, and exception handling separates receiving and handling error codes.

This feature clarifies programming ideas and enhances the readability of the code, making it easy for maintainers to read and understand.

Exception handling, known as error handling, provides a method for any unexpected or abnormal conditions that occur while the program is running.

Python exception handling uses keywords such as try,catch,else,finally to try operations that may not succeed, handle failures and normal situations, and clean up resources afterwards.

The syntax for catching and handling python exceptions is as follows:

# blocks where exceptions may occur

Try:

Block_try

# the first except form

Except Exception1:

Block_when_exception1_happen

# second form of except

Except (Exception2, Exception3, Exception4):

Block_when_exception2_or_3_or_4_happen

# the third form of except

Except Exception5, variance

Block_when_exception5_happen

# the fourth form of except

Except (Exception6, Exception7), variance

Block_when_exception6_or_7_happen

# the fifth form of except

Except:

Blok_for_all_other_exceptions

# handling when no exception occurs

Else:

Block_for_no_exceptions

# the last thing to do, regardless of whether there is an exception or not

Finally:

Block_anyway

Exception handling rules are divided into four parts:

The code that may produce an exception is written in the try block. If an exception occurs in the try block, the remaining code in the try block is terminated.

The code for exception judgment and occurrence, written in except, has five forms:

1 is that when an exception occurs, execute the code within the except block; 2) catch a variety of exceptions and execute the code; 3) that the caught exception can be converted into a variable; 4) catch a variety of exceptions into variables; 5) catch any exception

Each form of except capture can be defined multiple times, and the system will check one by one, but when one condition is met, the except block is executed, and the others are no longer checked and executed, similar to multiple if-else conditions.

Else is an optional module that defines what to do if no exception occurs

Finally is an optional module, and the code here will be executed regardless of whether the try module has an exception or not

To sum up, the try module is the program object, except is the exception capture submission and response, else is the handling when there is no exception, and finally is the last thing that must be executed, regardless of whether an exception occurs.

Exception happened

Process

Exception happened

List index out of range

Process

In addition to system predefined exceptions, you can also define your own specific logical exceptions.

Define the exception yourself, create a subclass that inherits the system exception, and throw the exception with the raise statement when it needs to be thrown.

The above is the analysis of python exception handling and object-oriented programming. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report