08 Python function classes and objects

08 Python function classes and objects

1. Function

1. Definition of function
 def 函数名 (参数列表):
 	 函数体
 	 return 返回值列表

The parameter list can be 0, 1 or more, and multiple parameters are separated by commas
Insert picture description here
Insert picture description here

2. Function call
函数名(实参)
3.tips

The function definition does not need to specify the parameter type, the interpreter automatically infers the
return value type, if there is no clear return value, the default return value is none

print() can be used to print a blank line

4. Parameter passing and parameter default values
def dup(str,times=2): #给出了一个默认值
	print(str*times)

Python stipulates that although optional parameters must be placed after non-optional parameters

5. The return value of the function

Can return one or more values, the return value can be a variable, an expression,
or no return value
Insert picture description here

6.lamada function (concise code usage)

The lamada reserved words are used to define anonymous functions (also known as lamada functions).
An anonymous function does not have a name, but returns the function name as the result of the
function. The definition of an anonymous function is equivalent to the following form as a normal function
Insert picture description here

def 函数名 (参数列表):
 	 return 表达式

Simply put, the lamada function is used to define a simple function that can be expressed in one line and returns a function type

f=lamada x,y: x+y#返回x+y的值

Insert picture description here
Features of lamada function:
simplify the code, but reduce the readability
. An anonymous function is defined, which
will not increase efficiency.
If it can be implemented with for ……in…… if, lamada function is
not used. If lamada function is used, do not include loops in the function. If so, it is recommended to define a function to complete

7. Variable parameter transfer (variable number of transferred parameters)
def <函数名> (<参数> ,*b):
	函数体
	返回值

*b is the name of the variable defined by yourself, b can be called anything
Insert picture description here

8. Global variables and local variables

Insert picture description here
Insert picture description here

2. Class and Object

The concept of objects in python is very broad, everything can be called an object, not necessarily an instance of a certain class. Built-in data types such as dictionaries, strings, lists, and tuples all have completely similar syntax and usage.
Such as:

"abc".split()
1. Definition of class
class 类名:
	方法定义
2. Class object

Class objects support two operations: attribute reference and instantiation.
Attribute references have the same standard syntax as all attribute references in Python: After the obj.name
class object is created, all names in the class namespace are valid attribute names.
Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/bj_zhb/article/details/104717832
Recommended