function
Function definition
Function is a reusable snippet of code used to implement a single, or associated function.
Function can improve the modularity of application and the reuse rate of code. In the previous learning process, I have used many built-in functions provided by Python, such as print(). Functions can not only use official functions, but also create their own functions. The functions written by ourselves are called user-defined functions.
Function creation
1. The keyword def is used to create the function, followed by the function name, followed by a bracket and marked in English:.
2. After the first step is completed, the carriage return will be indented. The statement under this indent belongs to the defined function and remains the same indent.
3. After defining a function, you sometimes need to pass in parameters, which must be written in parentheses. When there are no parameters, parentheses cannot be omitted
4. Return expression] used to end the function and selectively return a value to the caller. A return without an expression is equivalent to returning None
Example code:
def Function name(): Function content return Returned content
The most important principle for designing functions, the principle of single responsibility (one function can only do one thing) - > high cohesion
The ultimate principle of program writing: high cohesion (only do one thing, only do your own), low coupling - > high cohesion and low coupling
Function function
You can write a piece of repeated code with a function. When we need this repeated code later, we only need to change the passed parameters according to our own requirements, so we don't have to waste time writing a piece of repeated code. This process is also a function call
Write a function and call it
# Define a name called sum_ The function of num adds two numbers. A and B are the passed in parameters def sum_num(a, b): return a + b # Use return to return the result of the function # Call function if __name__ == '__main__': sum = sum_num(2,3) # Give the return value of the function to sum print(sum) # The value of the output sum is 5
if __name__ == '__main__': This allows us to use the following code only under this file. If there are other files calling the functions of this file, we don't have to execute the following code. We will write the following when calling functions in the future.
Parameters of function
If there is no return in the function, the function returns None by default. Functions are allowed to have no parameters, and parameters are allowed to have default values.
# Define a name called sum_ The function of num adds two numbers. A and B are the passed in parameters def sum_num(a=2, b=3): # Add default values for function parameters a and B, a=2,b=3 return a + b # Use return to return the result of the function # Call function if __name__ == '__main__': sum = sum_num() # When calling, if no parameters are passed in, the default values of a and B are 2,3 by default print(sum) # 5 sum = sum_num(3,4) # If a value is passed in to the parameter of the function, the parameter of the function will use the new value instead of the default value print(sum) # 7
Various uses of parameters:
def sum_num(a=0, b=0, c=0): return a+b+c # The number of parameters changes and the order changes # No parameters are passed in, and the default value is used for addition print(sum_num()) # 0 # If a parameter is passed in, the function will assign values in the order of the parameters passed in when defining the function, a,b,c; a=1,b=0,c=0 print(sum_num(1)) # 1 # Pass in two parameters, assign values in order, and use the default values for the rest print(sum_num(1,2)) # 3 # Pass in three parameters and assign them to a, B and C respectively print(sum_num(1,2,3)) # 6 # The passed in parameters can be out of order, but they need to be passed in the form of "parameter name = parameter value". print(sum_num(b = 3,c =5,a = 6)) # 14
Parameters with default values must be placed after parameters without default values
Variable parameters
When defining a function, we can not specify the number of parameters. When calling, we can pass in parameters as needed. The implementation method is to add * args in the function parentheses. Args is just a name, which can be changed to others.
# Define an accumulation function, uncertain the number of parameters passed in, and use ` * 'to define a variable parameter. def total(*args): total_num = 0 for value in args: total_num += value return total_num # Call the function and pass in different parameters print(total(1,2)) # 3 print(total(1,2,3)) # 6
Common modules and functions in python standard library
function | explain |
---|---|
abs | Returns the absolute value of a number. For example, abs(-1.3) will return 1.3. |
bin | Convert an integer to a binary string starting with '0b'. For example, bin(123) will return '0b1111011'. |
chr | Convert Unicode encoding into corresponding characters, for example: chr(8364) will return '€'. |
hex | Convert an integer to a hexadecimal string starting with '0x'. For example, hex(123) will return '0x7b'. |
input | Read a line from the input and return the read string. |
len | Gets the length of strings, lists, and so on. |
max | Returns the maximum value of multiple parameters or an iteratable object (which will be described later). For example, max(12, 95, 37) will return 95. |
min | Returns the minimum value of multiple parameters or an iteratable object (which will be described later). For example, min(12, 95, 37) will return 12. |
oct | Convert an integer to an octal string starting with '0o'. For example, oct(123) will return '0o173'. |
open | Open a file and return the file object (described later). |
ord | Convert the character to the corresponding Unicode encoding, for example: ord('€') will return 8364. |
pow | Exponentiation operation, for example: pow(2, 3) will return 8; pow(2, 0.5) will return 1.4142135623730951. |
Printout. | |
range | Constructing a range sequence, for example, range(100) will produce an integer sequence from 0 to 99. |
round | Round the value to the specified precision. For example, round(1.23456, 4) will return 1.2346. |
sum | Sum the items in a sequence from left to right. For example, sum(range(1, 101)) will return 5050. |
type | Returns the type of the object. For example, type(10) returns int; type('hello ') returns str. |
Functions are packages of code that are relatively independent and can be reused
Higher order function
Functions in Python are first-class functions (first-class citizens):
1. Functions can be used as parameters of functions
2. The function can be used as the return value of the function
3. Functions can be assigned to variables
If the function is used as the parameter or return value of the function, this method is called high-order function.
# Define a calculation function and call an addition function to add the incoming values def calculate(init_value, func, *args, **kwargs): # **args indicates that the parameter passed in must be in the form of a key value pair. total = init_value for arg in args: # Judge whether the passed in parameter belongs to integer or floating-point type, otherwise the corresponding operation cannot be performed. if type(arg) in (int, float): total = func(total, arg) for value in kwargs.values(): if type(value) in (int, float): total = func(total, value) return total def add(x, y): return x + y if __name__ == '__main__': # Add parameters in and out of the add function in the calculate function print(calculate(0, add, 11, 22, a = 33, b=44)) # 110 when a function calls a function, parentheses are not added
lambda function: a function that can be written in one sentence without a name. The only expression is the return value. Anonymous function for creating
# Use lambda function to create an anonymous function, which can be directly used for function calls. You do not need to use def to create functions print(calculate(0, lambda x,y:x+y, 11, 22, a = 33, b=44)) # 110
Anonymity means that a function is no longer defined in the standard form of def statement.
1. lambda is just an expression, and the function body is much simpler than def.
2. The body of a lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions.
3. lambda functions have their own namespace and cannot access parameters outside their own parameter list or in the global namespace.
4. Although lambda functions can only write one line, they are not equivalent to C or C + + inline functions. The purpose of the latter is to call small functions without occupying stack memory, so as to increase operation efficiency.
recursion
Function call itself ----- > recursion: inefficient, with a large number of repeated calculations
A function that calls itself directly or indirectly is called a recursive call
Whether a function calls another function or itself, it must converge quickly.
It can end in a relatively limited number of calls, rather than unlimited calls to functions.
If a function (usually a function called recursively) does not converge quickly, the following error will occur:
RecursionError: maximum recursion depth exceeded
main points
1. Recursive body
2. Convergence condition (recursive exit)
Application (factoring) (tower of Hanoi)
def fac(num): """ Factorization (recursion) :param num: number :return: Factorial """ if num == 0: # If there is no recursive exit, the code will loop return 1 else: # Internal call procedure, call down according to this, and then return the return value up # Call down and return the result up # return 5 * fac(4) 5*24 # return 4 * fac(3) 4*6 # return 3 * fac(2) 3*2 # return 2 * fac(1) 2*1 # return 1 * fac(0) 1*1 # return 1 return num * fac(num - 1) # 120 if __name__ == '__main__': pritn(fac(5)) # 120
# Hanoi Tower thought: move the largest one above to the middle column, put the largest one on the third column, and then move the one on the middle column to the third column. def hanoi(num, a, b, c): if num == 1: print(a, '---->', c) return else: hanoi(num - 1, a, c, b) hanoi(1, a, b, c) hanoi(num-1, b, a, c) if __name__ == '__main__': hanoi(3,'A','B','C') # Output results A ----> C A ----> B C ----> B A ----> C B ----> A B ----> C A ----> C
object-oriented
Python has been an object-oriented language since its design. Because of this, it is easy to create a class and object in Python.
Class: used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to each object in the collection. An object is an instance of a class.
Method: a function defined in a class.
Class variables: class variables are common to the entire instantiated object. Class variables are defined in the class and outside the function body. Class variables are usually not used as instance variables.
Method override: if the method inherited from the parent class cannot meet the needs of the child class, it can be overridden. This process is called method override, also known as method override.
Local variable: the variable defined in the method, which only acts on the class of the current instance.
Instance variable: in the declaration of a class, attributes are represented by variables, which are called instance variables. Instance variables are variables decorated with self.
Inheritance: that is, a derived class inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object.
Instantiation: create an instance of a class and a concrete object of the class.
Object: an instance of a data structure defined by a class. The object consists of two data members (class variables and instance variables) and methods.
Class definition
Class uses class to define a class
class classname: Class block
In the code block of a class, we need to write some functions. We said that a class is an abstract concept, so these functions are our extraction of the common dynamic features of a class of objects. The functions written in classes are usually called methods. Methods are the behavior of objects, that is, the messages that objects can receive. The first parameter of the method is usually self, which represents the object itself that receives the message. We can use self Properties or methods access properties, methods, etc. in a class.
# Define a student class class Student: def __init__(self,no,name,sex): # Initialize class attributes, no (student number), name (name), sex (gender) self.no = no self.name = name self.sex = sex def study(self,course_name): # Class method: learn and pass in a parameter learning course """study""" print(f'{self.name}I am learning{course_name}')
After defining the class, try calling it.
if __name__ == '__main__': stu1 = Student(123,'Da Chui Wang','male') # Instantiate a student object stu1 and pass in the required parameters print(stu1.no) # You can access the student number in the class and other properties stu1.study('python') # Call the study method in the class # output 123 Wang Dashui is learning python
Magic Methods
Magic method: – > with _ ''__ Form, method with special significance and purpose
__ init__----> The initialization method will be called automatically when calling the constructor syntax to create an object
__ str__-----> Get the string representation of the object, which will be automatically called when calling the print function to output the object
__ repr__ ----> The string representation of the object. When the object is placed in the container and the container is output with print, it will be called automatically
__ lt__-------> Originally, size comparison is not allowed. If the operator < is assigned to this class, the data in it can be compared with less than
Inheritance, polymorphism (Methods in the parent class are overridden by subclasses)
Inheritance definition: class name (inherited class name):
Subclasses can call the methods of the parent class or access the properties of the parent class.
Polymorphism: a subclass gives its own implementation version to the existing method of its parent class. This process is called method override
Polymorphism: in the process of rewriting a method, different subclasses can give different implementation versions of the same method of the parent class, then the method will show polymorphism at runtime, send the same message to different objects, and different objects perform different behaviors
Possible relationships between two classes:
is-a relationship: inheritance ----- > deriving from one class to another
Class class name (inherited class name) class Student(person)
has-a relationship: association ----- > take the object of one class as the attribute of the object of another class
General Association
Strong association: whole and part Association, aggregation and synthesis
use-a relationship: dependency ----- > an object of one class is used as a parameter or return value of another class
Multiple inheritance is allowed in python. A class has one or more parent classes
Try to use single inheritance
The inherited is called a parent class. The successor is called a subclass
Example: salary (monthly salary) settlement system
-Department Manager: fixed monthly salary, 15000 yuan -Programmer: Hourly settlement monthly salary, 200 yuan per hour -Salesperson: base salary+Commission, base salary 1800 yuan, sales 5%Commission Enter employee information and automatically settle monthly salary
from abc import abstractmethod class Staff: """Employee category""" def __init__(self, name): self.name = name @abstractmethod # The code can't be implemented. It represents abstract and needs to be imported into the library def get_salary(self): return class DivisionManager(Staff): # Inherit Employee class """division manager""" def __init__(self, name): super().__init__(name) # The parent class already has the common attribute name, so we can initialize the common attribute in the child class without initializing the common attribute. This method can be used to implement multiple common attributes separated by commas. def get_salay(self): return 15000 class Programmer(Staff): # Inherit Employee class """programmer""" def __init__(self, name, worktime_hour): super().__init__(name) self.worktime_hour = worktime_hour def get_salary(self): return 200 * self.worktime_hour class Salesman(Staff): # Inherit Employee class """salesperson""" def __init__(self, name, sales_volume): super().__init__(name) self.sales_volume = sales_volume def get_salay(self): return 1800 + (0.05 * self.sales_volume) if __name__ == '__main__': manager = DivisionManager('Da Chui Wang') print('Monthly salary of Department Manager:', manager.get_salay()) programmer = Programmer('Zhang San', 250) print('Programmer's monthly salary:', programmer.get_salary()) salesman = Salesman('Xiao Wang', 15000) print('Monthly salary of Salesperson:', salesman.get_salay())
Employees of three different occupations inherit the Employee class, and they can call properties and methods in the Employee class.
All three employees are interested in get in the parent class_ The rewriting of salay method realizes different salary calculation methods, which reflects the polymorphism of this method
Three pillars of object-oriented programming:
Abstraction: extracting commonalities (defining classes is an abstraction process, which requires data abstraction and behavior abstraction)
encapsulation: logically assemble data and functions that manipulate data into a whole (object). Hide implementation details and expose simple call interfaces.
inheritance: extend the existing class, create a new class, and reuse the code of the existing class.
polymorphism: send the same message to different objects, and different objects perform different behaviors.