python (program structure 2)

Keywords: Attribute

Exception handling Error
abnormal
1. Definition: errors detected at run time.
2. Phenomenon: when an exception occurs, the program will no longer execute downward, but will go to the call statement of the function.
3. Common types of exceptions:
- name error: variable not defined.
- type error: different types of data are operated on.
- index error: out of index range.
- attribute error: the object does not have an attribute with the corresponding name.
- key error: there is no key with the corresponding name.
– not implemented error: a method that has not been implemented.
- Exception base class Exception.
Handle
1. syntax:
try:
Statements that may trigger exceptions
except error type 1 [as variable 1]:
Processing statement 1
except error type 2 [as variable 2]:
Processing statement 2
Exception exception [as variable 3]:
Processing statement not of the above error type
else:
Statement without exception
finally:
Statement with or without exception

  1. Function: change the program from abnormal state to normal process.
  2. Explain:
    as clause is a variable used to bind the wrong object, which can be omitted
    The except clause can have one or more to catch a certain type of error.
    There can be at most one else clause.
    There can be at most one finally clause. If there is no except clause, it must exist.
    If the exception is not caught, it continues to pass to the upper layer (where it is called) until the program terminates.
"""
    //exception handling
"""


def div_apple(apple_count):
    person_count = int(input("Please enter the number of people:"))
    result = apple_count / person_count
    print("Everyone gets it%d An apple" % result)


# Writing 1:
# try:
#     div_apple(10)
# except Exception:
#     print("wrong")

# Writing 2:
# try:
#     div_apple(10)
# except ValueError:
#     print("cannot enter non integer")
# except ZeroDivisionError:
#     print("cannot enter zero")

# Writing 3:
# try:
#     div_apple(10)
# except ValueError:
#     print("cannot enter non integer")
# except ZeroDivisionError:
#     print("cannot enter zero")
# else:
#     print("split Apple successfully")

# Writing 4:
try:
    div_apple(10)
finally:
    print("No matter right or wrong, the logic of certain execution")
"""
    //Actively throw an exception
        //Fast delivery of error messages
    # 11:25
"""


class AgeError(Exception):
    """
        //Encapsulated data
    """
    def __init__(self, message="", error_id=0, code=""):
        self.message = message
        self.error_id = error_id
        self.code = code

class Wife:
    def __init__(self, name="", age=0):
        self.name = name
        self.age = age

    @property
    def age(self):
        return self.__age

    @age.setter
    def age(self, value):
        if 22 <= value <= 32:
            self.__age = value
        else:
            # raise Exception("I don't want it")
            # raise AgeError("I don't want to," 1001, "if 22 < = value < = 32")
            raise Exception("I don't want it",1001,"if 22 <= value <= 32")

# try:
#     w01 = Wife("double", 45)
# except AgeError as e:
#    print(e.error_id)
#    print(e.message)
#    print(e.code)

try:
    w01 = Wife("Geminis", 45)
except Exception as e:
   print(e.args[0])
   print(e.args[1])
   print(e.args[2])

raise statement
1. Function: throw an error to let the program enter an abnormal state.
2. Purpose: when the program is called at a deeper level, it is more difficult to transfer error information to the main function level by level. Therefore, it can directly transfer error information by throwing an exception artificially..
Custom exception
1. definition:
Class class name Error(Exception):
Definition init (self, parameter):
Super(). Init (parameter)
self. Data = parameter
2. invocation:
try:
....
raise custom exception class name (parameter)
....
Exception defines the except ion class as variable name:
Variable name. Data
3. function: encapsulates error information
iteration
Each repetition of the process is called an "iteration", and the result of each iteration will be the initial value of the next iteration. For example: loop to get the elements in the container.

"""
    //iteration
    //Exercise: exercise 03
"""
list01 = [4, 3, 56, 58, 52]
for item in list01:
    print(item)
# Written examination questions:
#    Conditions under which an object can participate in a for loop:
#           Object to get an iter ator object (the object must have a method of

# for loop principle
# 1. Get iterator object
iterator = list01.__iter__()
# 2. Get the next element
while True:
    try:
        item = iterator.__next__()
        print(item)
    # 3. Stop the loop if there is no element
    except StopIteration:
        break

Iteratable object
1. Definition: an object with the function "iterator" can return an iterator object.
2. grammar
– create:
class iteratable object name:
def iter(self):
return iterator
– use:
for variable name in can iterate over the object:
Sentence
3. principle:
Iterator = iteratable object. iter()
while True:
try:
Print (iterator. next())
except StopIteration:
break

"""
    //iterator
    //Exercise: exercise 04 05
"""
class SkillIterator:
    def __init__(self, data):
        self.__data = data
        self.__index = -1

    def __next__(self):
        self.__index += 1
        if self.__index > len(self.__data) - 1:
            raise StopIteration()
        return self.__data[self.__index]


class SkillManager:
    def __init__(self):
        self.__all_skills = []

    def add_skill(self, skill):
        self.__all_skills.append(skill)

    def __iter__(self):
        return SkillIterator(self.__all_skills)


manager = SkillManager()
manager.add_skill("Eighteen dragon subduing palms")
manager.add_skill("six miles holy sword")
manager.add_skill("Monkey steal peach")

# for item in manager:
#     print(item)

# for item in manager:
#     print(item)

iterator = manager.__iter__()
while True:
    try:
        item = iterator.__next__()
        print(item)
    except StopIteration:
        break
"""
    //Iterator -- > yield
    //Exercise: transforming the drawing Manager
        //Modifying the MyRange class
        exercise07
    //Requirements: commissioning procedure

"""

class SkillManager:
    def __init__(self):
        self.__all_skills = []

    def add_skill(self, skill):
        self.__all_skills.append(skill)

    # def __iter__(self):
    #     # yield core logic: Tags
    #     # General logic for generating iterator Code:
    #     # 1. Define the code before the yield statement into the next method body
    #     # 2. Take the data after the yield statement as the return value to the next method
    #     print("prepare")
    #     yield self.__all_skills[0]
    #     print("prepare")
    #     yield self.__all_skills[1]
    #     print("prepare")
    #     yield self.__all_skills[2]

    def __iter__(self):
        for item in self.__all_skills:
            yield item

manager = SkillManager()
manager.add_skill("Eighteen dragon subduing palms")
manager.add_skill("six miles holy sword")
manager.add_skill("Monkey steal peach")

for item in manager:
    print(item)

# iterator = manager.__iter__()
# while True:
#     try:
#         item = iterator.__next__()
#         print(item)
#     except StopIteration:
#         break

Iterator object iterator
1. Definition: an object that can be called by the next() function and return the next value.
2. grammar
Class iterator class name:
def init(self, aggregate object):
self. Aggregate object = aggregate object

def next(self):
if no element:
raise StopIteration
return aggregate object element
3. Description:
– an aggregate object is usually a container object.
4. Function: the user can get the elements in the aggregation object in a simple and clear way without knowing its internal structure.
generator
1. Definition: an iterative object that can provide data dynamically (loop through calculation and return once).
2. Function: in the process of circulation, it is not necessary to create a container to store the complete results, so as to save memory space. The larger the amount of data, the more obvious the advantage.
3. The above functions are also called delay operations or lazy operations. Generally speaking, they calculate results when they are needed, rather than building all results at once.
generator function
1. Definition: function with yield statement, return value is generator object.
2. grammar
– create:
def function name ():
...
yield data
...
– call:
for variable name in function name ():
Sentence
3. Description:
- calling the generator function will return a generator object without executing the function body.
– yield translates to "generate" or "generate"
4. Execution process:
(1) Calling the generator function automatically creates an iterator object.
(2) The generator function is only executed when the iterator object's \.
(3) Each time the yield statement is executed, the data is returned and the system leaves temporarily.
(4) Continue execution from the exit until the next call to the method.
5. Principle: the general rules for generating iterator objects are as follows
– place the previous code of the yield keyword in the next method.
– use the data following the yield keyword as the return value of the next method.

"""
    //generator function 
"""
"""
//Generator = iteratable object + iterator (primary)
class Generator:
    def __iter__(self):  
        return self 
    
     def __next__(self): 
        return ... 
"""

def my_range(end):
    start = 0
    while start < end:
        yield start
        start += 1

# Cycle once calculation once return once
for item in my_range(5):
    print(item)

# range = my_range(5)
# iterator = range.__iter__()
# while True:
#     try:
#         item = iterator.__next__()
#         print(item)
#     except StopIteration:
#         break
13 original articles published, 7 praised, 235 visited
Private letter follow

Posted by jesbin on Fri, 17 Jan 2020 08:00:42 -0800