Python Basics

Keywords: Python list

1, Fundamentals of Python language

1. Figures

1.1. Operator priority

Serial numberoperator
1Parentheses
2Power operator**
3Minus sign-
4Multiply *, divide /, divide /, remainder%
5Plus + minus-

1.2.

  • Numbers are divided into integer int, floating point float and complex number
  • Python supports handling large integers without overflow
  • Binary 0b (bin)
  • Octal 0o (oct)
  • hex 0x (hex)

1.3. Digital format output format

  • The return value of format is of string type
  • The first parameter is the number to format, and the second is the string representing the format
    For example:
x = 1234.56789


# Keep two digits after the decimal point, output result: '1234.57'
print(format(x, '0.2f'))   
   
# The numbers are aligned to the right in the area with a length of 12 characters, and one digit after the decimal point is reserved. The output result: '1234.6'      
print(format(x, '>12.1f'))   
       
# The numbers are left aligned in the area with a length of 12 characters, and three digits after the decimal point are reserved, followed by output 20. The output result: '1234.568 20'
print(format(x, '<12.3f'), 20)

# The numbers are aligned to the right in the area with a length of 12 characters, and one digit after the decimal point is reserved, and 0 is added in front of the number. The output result: '0000001234.6'
print(format(x, '0>12.1f'))

# The numbers shall be left aligned in the area of 12 characters in length, and one digit after the decimal point shall be reserved, followed by 0, and the output result: '1234.6000000'
print(format(x, '0<12.1f'))

# The numbers are aligned in the center of the area with a length of 12 characters, and two digits after the decimal point are reserved, followed by output 3. The output result: '1234.57 3'
print(format(x, '^12.2f'),3)

# Every thousand bits are separated by commas (,), and the output result is 1234.56789
print(format(x, ','))

# Every thousand digits are separated by commas (,) and two digits after the decimal point are reserved. The output result is 1234.57
print(format(x, ',.2f'))

# Output numbers in the form of scientific counting method, output result: 1.234568e+03
print(format(x, 'e'))

# Output numbers in the form of scientific counting method, and the mantissa retains 2 digits after the decimal point. Output result: 1.23E+03
print(format(x, '0.2E'))

2. Get input

2.1.

  • No matter what data is entered, the imput function returns as a string
  • The parameter of imput is the prompt output when waiting for input

2.2. Type conversion

functiondescribe
int(x)Convert x to decimal integer
float(x)Convert x to floating point number
complex(real [,imag])Create a complex number
str(x)Convert object x to string
list(s)Convert sequence s to list
tuple(s)Convert sequence s to tuple
chr(x)Convert integer x to character
ord(x)Converts the character x to an integer value
oct(x)Converts the integer x to an octal string
hex(x)Converts the integer x to a hexadecimal string

4. String basis

4.1.

  • The string is enclosed in single or double quotation marks
  • Escape character \ backslash. The content after the backslash is part of the string. Example: \ description the second \ is a character
  • String addition directly connects strings with a + sign
  • The repr function or writing r before the string can keep the string original characters.
  • For example: repl ("Hello\nWorld"), r"Hello\nWorld", at this time \ n will not be escaped and counted as two ordinary characters
  • Write at the end of the sentence \ you can write a string into multiple lines

2, Conditions, loops, and other statements

1. Output, assignment, indentation

1.1.print function:
print(a,b,c,d,e,f,g)

  • Multiple parameters are output end to end. There is a space by default
  • Add sep = "," at the end of the parameter to change the default space into a comma (,)
  • Add end = "" at the end of the parameter, which changes the default line break ending character to a space ending character
  • End = "" is added at the end of the parameter, which changes the default line break ending character to the end of the string with length 0, that is, the line break effect is cleared

1.2. Sequence unpacking, chain assignment and incremental assignment

  • x,y=100,"a";
  • x=y=50;
  • x+=20;

1.3. Indent

  • Each line of a code block should be indented by the same amount
  • The colon represents the beginning of the code block, and each statement in the code block is indented
  • When you go back to the same indent as the block, it means that the current block has ended

2. Conditions and conditional statements

2.1. Boolean values and Boolean variables

  • Each type of value can be interpreted as a Boolean value
  • True is 1.False is 0
  • You can use the bool function to convert other types of values to Boolean values
print(bool(""))              #False
print(bool(''))              #False
print(bool("Hello"))         #True
print(bool([]))              #False
print(bool([1,2,3]))         #True
print(bool(0))               #False
print(bool(20))              #True

2.2. Comparison operator

Logical expressiondescribe
x==yx equals y?
x>=yx is greater than or equal to y?
x<=yx is less than or equal to y?
x!=yx is not equal to y?
x is yAre x and y the same object?
x is not yx and y are not the same object?
x in yIs x a member of y?
x not in yIs x a member of y?
  • Strings can also be compared with logical expressions
  • and or not logical operation
  • ==Only the value is judged, and is judges whether it points to the same location and the same object

2.3.if ,else,elif
From if, else, elif to colon (:) are Boolean

2.4.assert assertion statement

value=20
assert value<10 or value >30,'value The value must be within 10~20 between'

Throw an exception directly. The reason for the exception is: 'value must be between 10 and 20'

3. Circulation

3.1.range function

  • numbers=range (11000), then numbers=[1,2... 998999]
  • for i in range (100) traverses 99 from 0

3.2.

x=0
while x<100:     #for i in range (100):
    print(x)     #     print(i) 

3.3.break out of loop continue to jump out of a single loop
Generally, it is only placed in the if statement

4.exec and eval

4.1.

  • The functions of exec and eval are the same. ecex does not return a value, and eval will return a result value
i={}
eval("print(a+b)",i,{'a':1,'b':2})
  • The first parameter print(a+b) represents the string to be executed, and i represents the parameter passed to i for calculation,
    {'a': 1, 'b': 2} represents the initialization of the variable to be executed. What value is passed to the variable

3, Lists and tuples

1. Define sequence

  • The sequence can be any type of value, variable or other sequence (forming a two-dimensional sequence)
names = ["Bill", "Mike"]
numbers = [1,2,3,4,5,6]
salary=[3000.0,4000.0,5000.0]
flags = [True,False,True,True]
values = [names,numbers,salary,flags,['a','b']]
for value in values:
    print(value)

2. Basic operation of sequence

2.1. Index

  • Strings and sequences can be indexed directly
a=input()[2]
flags = [True,a,True,True]
print(flags[1][0])  #Input 123, output 3

2.2. The slice is also closed on the left and open on the right

  • [a,b,c]
  • a. Parameter b only represents the position, parameter c represents the step size, and if c > 0, cut out a~b
  • If C < 0, slice from the end and cut out b~a
  • If the parameter is not written, there is no limit, and the step size cannot be 0

2.3. Addition of sequences

  • Sequences and sequences can be connected end to end, and strings and sequences cannot be added directly
print([1,2,3] + [6,7,8])    # Operation results: [1,2,3,6,7,8]
print("Hello" + " world")     # Run result: Hello world

print([1,2,3] + ["hello"])    
# Take the string as an element of the sequence and run the result: [1,2,3,"hello"]
print([1,2,3] + ['h','e','l','l','o'])
# Operation result: [1,2,3,'h','e','l','l','o']
print([1,2,3] + "hello")     
# Throw an exception. The sequence cannot be added directly to the string

2.4. Multiplication of sequences

  • Multiplying int n by a sequence generates a sequence that repeats n times
print('hello' * 5)
#hellohellohellohellohello
print([20] * 10)
# [20, 20, 20, 20, 20, 20, 20, 20, 20, 20]
  • len, max, min functions of sequences

3. Basic operation of list

  • Delete list element del has no return value. remove (value) returns the number of deleted elements (only the first occurrence position can be deleted)
  • Pop (position) deletes the number of parameter positions and returns
  • Slice assignment: insert element, delete element, add tail element
numbers = [1,6,7]
numbers[1:1] = [2,3,4,5]#It is equivalent to inserting elements, but it will not become two-dimensional
print(numbers)
# [1, 2, 3, 4, 5, 6, 7]    
numbers[1:4] = [] 		#This is equivalent to deleting elements   
print(numbers)
# [1, 5, 6, 7]   
numbers[9:] =number		#Equivalent to adding elements to the tail   
print(numbers)
#[1, 5, 6, 7, 1, 5, 6, 7]

4. List method

methodeffect
append(x)Returns the list with the new value x inserted at the end of the list
clear()Return to empty list
copy()Returns an identical sequence
cout(x)Returns the number of occurrences of x
a.extend(x)No return value for connecting a and x
index(x)Returns where x first appeared
insert(x,y)Returns a list of y inserted at x
pop(x)Returns the value of the x position and deletes the element at that position
remove(x)Returns a new list that deletes the first occurrence of x
reverse()Returns a new list placed upside down
sord()Returns a new list in ascending order
sorded()No return value
print("----test copy method-----")
a = [1,2,3]
b = a                            # a and b point to the same list
b[1] = 30                           # Modify the element value of List b, and the corresponding element value in list a will also change
print(a)                        # Operation result: [1, 30, 3]

aa = [1,2,3]
bb = aa.copy()                    # bb is a copy of aa
bb[1] = 30                        # Modify the element value in bb, and the element value in aa will not change
print(aa)                        # Operation result: [1, 2, 3]

print("----test extend method-----") #List + number is inefficient and not used
a = [1,2,3]
b = [4,5,6]
a.extend(b)                     #  The b list is followed by the a list, and the extend method does not return a value
print(a)                        #  Operation result: [1, 2, 3, 4, 5, 6]

print("----test pop method-----")
numbers = [1,2,3]
#  The pop method returns the deleted element value
print(numbers.pop())                #  Delete the last element value in the numbers list and run the result: 3
print(numbers.pop(0))                #  Delete the value of the first element in the numbers list and run the result: 1
print(numbers)                        #  Operation result: [2]

print("----test sort method-----")
numbers = [5,4,1,7,4,2]                
numbers.sort()                       # Sorts the element values in the numbers list in ascending order (default)
print(numbers)                        # Operation result: [1, 2, 4, 4, 5, 7]

values = [6,5,2,7,"aa","bb","cc"]
# The element types of the list to be sorted must be comparable. String and numeric types cannot be directly compared, otherwise an exception will be thrown
# values.sort()                      #  Throw exception

# Using the sorted function
x = [7,6,4,8,5]
y = sorted(x)                       #  Sort copies of x
print(x)                            #  Operation result: [7, 6, 4, 8, 5]
print(y)                    # Operation result: [4, 5, 6, 7, 8]

# The sorted function can sort any sequence, such as a string
print(sorted("geekori"))    # Running result: ['e ',' e ',' g ',' I ',' k ',' o ',' R ']

x = [5,4,1,7,5]
x.sort(reverse=True)        # Sort the element values in the list x in descending order
print(x)                   # Operation result: [7, 5, 5, 4, 1]

5. Tuple

5.1. Tuple creation:

a=1,
b=(1,)
c=(1,2,3)
print(a,b,c,end="") 
#(1,) (1,) (1, 2, 3)

5.2.

  • Convert strings and lists to tuples:
  • Tuple ([1,2,3]) returns a (1,2,3) tuple

4, String

1. Basic operation of string

  • Indexes
  • section
  • multiplication
  • in
  • len,max,min

2. Format string

2.1. Three parameter transfer methods
1. Tuple parameters

  • Add% to string a to define the string template
  • Specify a tuple b, which is the parameter value to be transmitted
  • a%b
#  Define string template
formatStr = "Hello %s. Today is %s"
#  Initialization string template parameter value. Tuples must be used here, and lists cannot be used
values = ('Mike', 'Wednesday')
#  format string 
print(formatStr % values)
  • Display%, hit two%%. Display $, type two$$

2. Template string template class

  • First import the Template class in the string module
  • Create a Template in the parameters of Template()
  • Pass parameters with substitute()
# Reference the Template class in the string module
from string import Template
template1 = Template("$s Is my favorite programming language, and $s Powerful")
# Specifies that the value of the format parameter s is Python
print(template1.substitute(s='Python'))
# When the format parameter is part of a string, in order to distinguish it from other parts of the string,
# You need to enclose the formatted parameter variables with a pair of braces
template2 = Template("${s}stitute")
print(template2.substitute(s='sub'))

3. String format () method

  • Curly braces in sequential parameter string
  • Keyword parameter is the curly bracket in the parameter string
  • Specify the pass parameter in braces
#You can assign values sequentially and by keyword parameters
s3 = "Today is {week}, {},the {} temperature is {degree} degrees."
print(s3.format("aaaaa", 77777, degree = 22, week ="Sunday"))
#You can pass the keyword parameter assignment and specify the assignment, 1 specifies 77777, and 0 specifies AAA
s4 = "Today is {week}, {1},the {0} temperature is {degree} degrees."
print(s4.format("aaaaa", 77777, degree = 22, week ="Sunday"))
#You can pass keyword arguments instead of list names
namelist = ["Bill", "Gates"]
print("Mr {name[1]}".format(name = namelist))
#You can also pass keyword parameters instead of module names
import math
s5 = "The {mod.__name__} module defines the value {mod.pi} for PI"
print(s5.format(mod = math))

4.fomat () method and type character of tuple parameter

Type characterdescribe
aOutput characters in Unicode encoding
cInterpret integers as characters
dFormat integer
sformat string
uFormat unsigned integer
bFormat unsigned binary number
oFormat unsigned octal number
xFormat unsigned hexadecimal number
XFormat unsigned hexadecimal number (upper case)
fFormat floating-point numbers to specify the precision after the decimal point
eFormatting floating point numbers with scientific counting
EThe function is the same as e. format floating-point numbers with scientific counting method
gAbbreviations for F and e, less than or equal to 6 bits is f, higher than the six bit scientific count e
GAbbreviations for F and E
pFormat the address of a variable with a hexadecimal number
%Format the value as a percentage

5. Field width, precision, alignment, filled with 0, filled with symbol

from math import *
print('{0:<010.2f}\n{0:^010.2f}\n{0:>010.2f}'.format(pi))

  • The 0 before the colon represents the 0 th element
  • < align left > align right after colon ^ Center
  • The first 0 after the colon is filled with 0
  • 10 means that the field length is 10
  • . 2 stands for two decimal places
from math import *
print('{0:@<10.2f}\n{0:@^10.2f}\n{0:@>10.2f}'.format(pi))

  • The 0 before the colon represents the 0 th element
  • The first symbol @ after the colon indicates that it is filled with @
  • < align left > align right after colon ^ Center
  • 10 means that the field length is 10
  • . 2 stands for two decimal places

3. String method

Method namedescribe
center(a,b)Returns a string formatted with a width centered and filled with b
find(a,b,c)Return to find the starting position of the first occurrence of a, starting from position b to position c, close left and open right, and return - 1 if not found
s.join(list)Add the string s after each element of the list
s.split(a)Splitting the string s with a is the inverse of join()
lower() upper()Returns all lowercase strings and all uppercase strings
capwords()Returns a string in which all English words are capitalized
s.replace(a,b)Change string a in string s to b
s.strip(" *&")Cut the "* &" before and after the string
#Usage of join
list=['1','2','3','4','5']
s="*"
print (s.join)
#1*2*3*4*5

#Use of strip
print("***  &* Hello& *World**&&&".strip(" *&"))
#Hello& *World

translate method and maketrans method

  • Create replacement table with maketrans method
  • Replace one by one with the translate method according to the replacement table
  • The first and second parameters of makestrings represent the string to be replaced respectively, and the third parameter is the string to be deleted. Delete all
  • maketrans is called through the string s, which returns a dictionary
    Format:
s = "I not only like python, but also like kotlin."
table= s.maketrans("ak", "$%", " ")
print(table)
print(len(table))
print(s.translate(table))

5, Dictionary

1. Create and use dictionaries

1.1. Definition dictionary

  • Keys are used to map values. There is a unique key in a dictionary corresponding to different values. The key is id
  • Defined in braces, each key value is separated by commas and keys and values are separated by colons
  • dict(a) function to create a dictionary: returns a dictionary converted from a list of only two elements
  • Dictionaries can always be nested, so they can be multi indexed
  • The index is the key of the cable, not the position of the cable. There are only keys and no positions in the dictionary
#Direct definition
d0={'Bill': '1234', 'Mike': '4321', 'Marry': '7753'}
#Define with dict
items=[["Bill","1234"],["Mike","4321"],["Marry","7753"]]
d1=dict(items)
print(d1)

#All output: {Bill ':'1234', 'Mike':'4321 ',' Mary ':'7753'}

1.2. Basic operation of Dictionary:
Value taking, assignment, adding key value pairs, calculating the number of key value pairs, finding keys, deleting key value pairs

items= {"zero":"Fatal Frame","one":"one","two":"two"} #definition
a=items["one"] 		#Value
print(a)
items["two"]="II"	#assignment
items["three"]="three"	#Add key value pair
b=len(items)		#Calculate the number of key value pairs
print(b)
if "one" in items: print("\"one\" is in items")#Find key
del items["zero"]	#Delete key value pair
print(items)

1.3. Format string with dictionary
format_ The map function replaces all keys with values

2. Dictionary method

Method namedescribe
s.clear()Empty all elements in dictionary s
s.copy(a) s.deepcopy(a)Returns the shallow and deep copy dictionaries a
fromkeys()Returns a new dictionary created with keys. Each key corresponds to the same value. The first parameter is the key sequence, and the second parameter corresponds to a unified value
get(key,a)Returns the value corresponding to the key. The advantage is that when the key does not exist, it will return the specified value a and will not throw an exception
items()Returns a list of tuples of all key value pairs in the dictionary, which is used to iterate over the for loop structure
keys()Returns a list of all keys in the dictionary for iteration of the for loop structure
value()Returns a list of values in the dictionary
pop()Return the specified key value pair and delete the key value pair (the indexes are the keys of the search, not the position of the search. There are only keys and no positions in the dictionary)
popitem()Returns the last key value in the dictionary and deletes the key value pair
setdefault()If the key does not exist, add the key value pair. If the key exists, ignore and do not modify. The value of the added key value pair is returned, or ignore the value that does not modify
d1.update(d2)Update and overwrite another dictionary d1 with one dictionary d2
  • Shallow copy is all the layers below the second layer. The original dictionary and the new dictionary point to the same value.
  • The deeply copied dictionary is completely separated from the elements of the original dictionary.

6, Functions

1. Function basis

1.1.

  • def function name (parameter):
  • There is no need to specify the data type and return value type
  • Function with no return value. Output None when output

2. Function parameters

2.1.

  • Values, strings, and bool types are passed as values in functions and are only valid on the stack
  • Composite types (lists, dictionaries, objects) are reference types in functions. Pointers point to the same location and can change the value of external variables of the function
  • Since there is no need to specify the parameter type, parameters can be passed either by location or by keyword assignment:
def greet(greeting,name) :
    return "Greetings:"+greeting+"  full name:"+name
print(greet(name="Li Ning",greeting="Hello"))
#Greetings: Hello Name: Li Ning
  • The keyword parameter must be after the position parameter
  • The same formal parameter cannot pass location parameters and keyword parameters at the same time
  • You can specify default values for parameters. All parameters after specifying default values must have default values

2.2.

  • Variable parameter: the number of parameters is variable
  • Add a before the parameter*
  • Variable parameters are represented as tuples within a function
  • A variable parameter cannot be followed by a normal parameter unless it is a parameter with a default value or a keyword parameter

2.3. Pass sequence into function as parameter

  • All parameters are string type by default
  • By using the value transfer method of variable parameters, sequences can be passed in, and the value of each sequence can be passed in as a single parameter
  • Two parameters can be added during definition, as well as during parameter transfer. No, No
def add1(x,y,z):
    return x + y + z
print(add1(1,2,3))
#6
list = [2,3,4]   # You can use lists or tuples
print(add1(*list))
#9
def add2(*numbers):
    result = 0
    for number in numbers:
        result += number
    return result
print(add2(1,2,3,4,5))
print(add2(*list))
#15
#9
dict = {'x':100, 'y':200, 'z':12}
print(add1(**dict))
#321
def add3(**numbers):
    result = 0
    for item in numbers.items():
       result += item[1] 
    return result
print(add3(**dict))
#312


3. Scope and recursion

3.1.

  • py local variables need to be assigned before use
  • The scope of the function is to take values from the superior step by step

3.2. Factorial and Fibonacci series

def jc(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * jc(n - 1)
print(jc(10))


def fibonacci(n):
    if n == 1:
        return 0
    elif n == 2:
        return 1
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10))

7, Classes and objects

1. Create classes and add private methods

  • class name:
  • The first parameter, self, represents the instance of the current class. You can use self to refer to the instance in the class (self can be represented by all variable names. It's just a habit to use self here)
  • Class member variables are defined and called with (self.)
  • When creating an object, there is no new. Everything else is the same as java
  • Like spacetime, pass, and indent

Private method private in py:

  • Double underline before method name_
  • The principle is that the method name is changed to_ Class name_ Method name ()
class MyClass:  #Define class
    def getName(self):
        return self.name
    def setName(self, name):
        self.name = name
        self.__outName()
    def __outName(self):
        print("Name = {}".format(self.name))
myClass = MyClass()  #create object

import inspect   #Import the inspect module and find out all the method names in a class
methods = inspect.getmembers\
(myClass, predicate=inspect.ismethod)
for method in methods:
    print(method[0])
print("------------")
myClass.setName("Bill")
print(myClass.getName())
myClass._MyClass__outName() #Using method instances in the myclass object
#print(myClass.__outName())

Output result: therefore, the outname () method no longer exists in this class. Change the name to_ MyClass__outName() method

2. How to inherit one or more classes

  • Class subclass name (parent class name, parent class name, parent class name):
  • If the method has the same name, the parent class written in the front will overwrite the parent class written in the back. It will not be overloaded. It only depends on the method name, not the number of parameters
  • py has no interface. You can use hasattr(a,b) function and gatattr(a,b,c) function to detect whether there is method B in object a
class MyClass:
    def method1(self):
        print("method1")
my = MyClass()
if hasattr(my, 'method1'):
    my.method1()   #method1
else:
    print("method1 Method does not exist")
def sum():
    return 1+2+3+4
method = getattr(my, 'method2',sum)
print(method())  #10

3. How to detect the inheritance relationship between classes

3.1.

  • issubclass function, the first parameter is a subclass, and the second parameter is an ancestor class
  • If there is an inheritance relationship, return True; if there is no inheritance relationship, return false
  • __ (all double bottom lines)__ bases__ Function returns the immediate parent of the class
  • All classes are subclasses of the object class
  • isinstence(a,b) function to judge whether object a is an instance of class B
  • The first parameter is the object and the second parameter is the class
class YeYe:
    def f1(self):
        return 50
class BaBa(YeYe):
    def f2(self):
        print("f2")
class ErZi(BaBa):
    def f3(self):
        print("f3")
class MoshengRen:
    def method(self):
        return 40

print(issubclass(ErZi, YeYe))  #T
print(issubclass(ErZi, BaBa))  #T
print(issubclass(ErZi, MoshengRen)) #F

print(ErZi.__bases__)#Ba
print(BaBa.__bases__)#Ye

Sunlight = ErZi()
print(isinstance(Sunlight, ErZi))#T
print(isinstance(Sunlight, BaBa))#T
print(isinstance(Sunlight, YeYe))#T
print(isinstance(Sunlight, MoshengRen))#F

8, Abnormal

1. Throw an exception

  • raise throws an exception
  • Class Exception class name (Exception): customize the Exception class
class WarpdriveOverloadException(Exception):
    pass

warpSpeed = 12

if warpSpeed >= 10:
    raise WarpdriveOverloadException\
    ("The warp engine is overloaded. Please stop or eject the warp core, otherwise the spacecraft will explode")

2. Catch exceptions

  • Run the code in try first. If an exception is encountered, go to the exception statement directly
x = None
while True:
    try:
        if x == None:
            x = int(input("Please enter the numerator:"))
        y = int(input("Please enter denominator:"))
        print("x / y = {}".format(x / y))
        break;
    except :
        print("Denominator cannot be 0, please re-enter denominator!")
  • Catch multiple exceptions, write out the throw of each exception, and then implement the function in the try statement. Finally, write multiple (except Exception:) statements
  • You can write multiple exceptions after exception to handle multiple exceptions at the same time
  • Exception exception as e: throw exception object E
  • The statements in the finally statement must be executed
class NegativeException(Exception):
    pass
class ZeroException(Exception):
    pass

class SpecialCalc:
    def add(self,x,y):
        if x < 0 or y < 0:
            raise NegativeException
        return x + y
    def sub(self,x,y):
        if x - y < 0:
            raise NegativeException
        return x - y
    def mul(self,x,y):
        if x == 0 or y == 0:
            raise ZeroException
        return x * y
    def div(self,x,y):
        return x / y

while True:
    try:
        calc = SpecialCalc()
        expr = input("Enter an expression to evaluate, for example, add(1,2): ")
        if expr == ":exit":
            break;
        result = eval('calc.' + expr)
        print("Calculation results:{:.2f}".format(result))
    except NegativeException:
        print("******Negative anomaly******")
    except ZeroException:
        print("******Exception with operand 0******")
    except ZeroDivisionError:
        print("******Denominator cannot be 0******")    
    except:
        print("******Other exceptions******")
        

3. Exception, function and stack tracking

  • If the innermost function throws an exception and is not handled, the exception will propagate until it reaches the top function and interrupt the program

9, Methods, properties, and iterators

1. Construction method

  • def init(self,a):
  • The method name of the construction method is init, and two lower lines are added before and after each__ init__
  • The subclass overrides the parent method and directly overrides the parent method
  • You can only use self in a constructor to create member variables of a class, unless they are static variables

1.2.super function calls the method of the parent class

  • super(SongBird,self).init(hungry)
  • The first parameter represents the class name. If you inherit the method of the parent class, you will not write the parameter. If you inherit from the grandfather class, write the class name of the father class as the parameter
  • The second parameter is self, which represents the current instance
  • What method can I call with (.) later
class Animal:
    def __init__(self):
        print("Animal init")
class Bird(Animal):
    def __init__(self, hungry):
        super().__init__()
        self.hungry= hungry
    def eat(self):
        if self.hungry:
            print("I've eaten worms!")
            self.hungry = False
        else:
            print("I've eaten. I'm not hungry!")
b = Bird(False)
b.eat()
b.eat()

class SongBird(Bird):
    def __init__(self,hungry):
        super(SongBird,self).__init__(hungry)
        self.sound = 'Borrow it from heaven for another 500 years'
        
    def sing(self):
        print(self.sound)

        
sb = SongBird(True)
sb.sing()
sb.eat()

2. Properties

2.1. Attributes are member variables

  • __ dict__ It is a system built-in member variable, which is used to save the values of all attributes in the object
  • Use: self. dict [member variable name] = value

2.2. Attributes in the monitoring object:

  • The getattr(self,name) method monitors the read operation of all attributes
  • The setattr(self,name) method monitors all attribute writes
  • The delattr(self,name) method monitors the deletion of all attributes

These special methods are called automatically

3. Static method and class method

  • Static method calls do not need to create an instance. It is similar to a function, and the definition is the same as a function. Just add a decorator @ staticmethod before
  • Class methods and static methods can be called in instance methods, but not vice versa
class MyClass:
    name = "Bill"
    def __init__(self):
        print("MyClass The constructor of is called")
        self.value = 20
    @staticmethod
    def run():
        print(MyClass.name)
        print("MyClass Static method of run Called")
    @classmethod
    # Here, self is metadata
    def do(self):
        print(self)
        print(self.name)
        print('Call static method run')
        self.run()
        # If it is a class method, the member variables in self cannot be accessed
        #print(self.value)
        print("Member method do Called")
    def do1(self):
        print(self.value)
        print(self.name)
        print(self)
        
MyClass.run()  #Call static method
print('----------------')
c = MyClass() #Call constructor
print('----------------')
MyClass.do()  #c.do() calls class methods
print('----------------')
c.do1()   #Call member method

4. Iterator and generator

  • In order to save memory resources, iterators and generators obtain data from data sources one by one. The former takes classes as carriers and the latter takes functions as carriers
  • Iterator: iter() method that returns the object itself
  • The next() method calls the next iteration object
  • Generator: return value with yield
#An iterator that iterates the rows of a right triangle infinitely
class RightTriangle:
    def __init__(self):
        self.n=1            #Define a variable n to represent the current number of rows
    def __next__(self):#Get the string of each line by string multiplication
        result='*' * (2*self.n - 1)
        self.n += 1
        return result
    def __iter__(self):
        return self        #The method must return an iterator
rt=RightTriangle()
for i in rt :                #Iterate over iterators
    if len(i) > 20:       #Control the range of the output, otherwise it will iterate indefinitely
        break;
    print(i)
# Recursive generator
def enumList(nestedList):
    try:
        for subList in nestedList:
           for element in enumList(subList):
                yield element
    except TypeError:
        yield nestedList
        
nestedList = [4,[1,2,[3,5,6]],[4,3,[1,2,[4,5]],2],[1,2,4,5,7]]
for num in enumList(nestedList):
    print(num, end=' ')


Posted by PHPNewbie55 on Wed, 10 Nov 2021 08:12:50 -0800