Python 3 object-oriented programming, error and exception handling

Posted by kevgais on Tue, 07 May 2019 10:40:04 +0200

Class and instance

Classes are abstract templates, and instances are concrete "objects" created according to classes.

Terminology explanation

Class: A collection of objects that describe the same properties and methods. It defines the properties and methods common to each object in the set. Objects are instances of classes.
Method: Functions defined in the class.
Class variables: Class variables are common throughout the instantiated object. Class variables are defined in the class and outside the body of the function. Class variables are usually not used as instance variables.
Data Members: Class variables or instance variables are used to process data related to classes and their instance objects.
Method rewriting: If the method inherited from the parent class can not meet the needs of the subclass, it can be rewritten. This process is called override, also known as method rewriting.
Instance variables: Variables defined in the method that only act on the class of the current instance.
Inheritance: A derived class inherits the fields and methods of the base class. Inheritance also allows an object of a derived class to be treated as a base class object. For example, there is a design where a Dog-type object is derived from an Animal class, which simulates an "is-a" relationship (example, Dog is an Animal).
Instance: Create an instance of a class, a concrete object of the class.
Object: An instance of a data structure defined by a class. Objects include two data members (class variables and instance variables) and methods

Definition class

class Student(object):
    pass
#Classes usually begin with uppercase letters, and object means that the class is inherited from that class (if the top class can't find inheritance, write object directly)

Class initialization

The first parameter of the init method is always self, representing the created instance itself, so within the init method, various attributes can be bound to self.

class Int:
    def __init__(self, a, b):  #self represents an example
        self.r = a
        self.i = b
x = Complex(3, 4)  #Instantiating objects requires passing two parameters
print(x.r, x.i) 
//Output: 34

Class object

Class objects support two operations: attribute reference and instantiation

#Define Student classes:
class Student:
    id = 123
    def f(self):
        return 'hello world'

#instantiate
x = Student()

#Attributes and methods for accessing classes:
print("student Properties:",x.id)
print("student Method:",x.f())
//Output results:
student Attribute: 123
student Method: hello world

Class method

Within the class space, def keywords can be used to define a method for a class. Unlike general function definitions, a class method must contain the parameter self and be the first parameter:

class Student:
    #Define basic attributes
    name = ''
    age = 0
    #Set access restrictions: Define private attributes that cannot be accessed directly outside the class
    __weight = 0
    #Define the construction method
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s say: I %d Year old." %(self.name,self.age))

# instantiate
p = people('xiaoming',10,30)
p.speak()
//Output results:
xiaoming say: I'm 10 years old.

Class Inheritance: Single Inheritance and Multiple Inheritance

class Student:
    name = ''
    age = 0
    __weight = 0
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s say: I %d Year old." %(self.name,self.age))

#single inheritance
class people(Student):
    grade = ''
    def __init__(self,n,a,w,g):
        #Call the constructor of the parent class
        Student.__init__(self,n,a,w)
        self.grade = g
    #Method of overwriting parent class
    def speak(self):
        print("%s say: I %d Years old, I'm reading %d grade"%(self.name,self.age,self.grade))

#Multiple Inheritance Preparedness
class speaker():
    topic = ''
    name = ''
    def __init__(self,n,t):
        self.name = n
        self.topic = t
    def speak(self):
        print("My name is %s,I am a speaker. The theme of my speech is %s"%(self.name,self.topic))

#multiple inheritance
class sample(speaker,people):
    a =''
    def __init__(self,n,a,w,g,t):
        people.__init__(self,n,a,w,g)
        speaker.__init__(self,n,t)

test = sample("Tim",25,80,4,"Python")
print(test.speak())   #The method name is the same. By default, the method of the parent class in parentheses is called.
//Output results:
//My name is Tim. I'm a speaker. The theme of my speech is Python.

Class's proprietary methods

_ init_: Constructor, called when an object is generated
 _ del_: Destructor, used when releasing objects
 _ repr_: Printing, Conversion
 _ setitem_: assign values by index
 _ getitem_: Get values by index
 _ len_: Get Length
 _ cmp_: Comparisons
 _ call_: Function call
 _ add_: Addition
 _ sub_: subtraction
 _ mul_: Multiplication
 _ div_: division operation
 _ mod_: Redundancy Operations
 _ pow_: Multiplier

Error and exception handling

Python has two types of errors that are easy to identify: grammatical errors and exceptions
When running a Python program, errors can occur even if the grammar is correct. Errors detected during runtime are called exceptions.

exception handling

The try statement works as follows.
First, execute the try clause (between the key word try and the key word except)
If no exception occurs, ignore the except clause, and the try clause ends after execution.
If an exception occurs during the execution of the try clause, the rest of the try clause will be ignored. If the exception type matches the name after except, the corresponding except clause will be executed. Finally, the code after the try statement is executed.
If an exception does not match any except, the exception is passed to the upper try.

###A try statement may contain multiple except clauses to handle different specific exceptions. At most one branch will be executed;
###The except clause can handle multiple exceptions simultaneously, and these exceptions will be placed in parentheses to form a tuple.
###The try except statement also has an optional else clause, which, if used, must be placed after all except clauses. This clause will be executed when no exception occurs in the try clause.

import sys
try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err: 
    print("OS error: {0}".format(err))
except (RuntimeError, TypeError, NameError):
    print("Could not convert data to an integer.")
else:
    print('ok !')
    f.close()

throws

The only parameter in raise specifies the exception to be thrown. It must be an instance of an exception or an exception class.

Write code slices here.

Key contents

Reference article:
Liao Xuefeng, Newbie Course, w3cschool Course

Topics: Python Attribute REST