Writing functions
def is the executable code. The Python function is a new statement that is portable, that is, def. Unlike a compiled language like C, DEF is an executable statement that does not exist and that Python does not exist until the DEF is run. In fact, if statements, while statements are raised to be nested in other Def, are legitimate.
Def creates a function object and assigns it to a variable name. when Python runs to the DEF statement, a new function object is generated and assigned to the function name. Just like all assignments, the function name becomes a reference to a function. function objects can be assigned to other variable names and saved in the list. Functions can also be created through lambda expressions.
Lambda creates an object but returns it as a result. This feature allows us to put the function definition into a place where the syntax of a DEF statement does not work. belongs to advanced concepts.
Return sends a result object to the caller.
yield plays a result object to the caller, but remembers where it left off. functions such as generators can also return values through the yield statement and suspend their state so that they can later recover state, which is a high-level concept.
Global declares a module-level variable and is assigned a value. by default, all objects that are assigned to a function are local variables of the function and exist only during the run of the function. In order to assign a variable name that can be used throughout the module, the function needs to be enumerated in the global statement.
Functions are passed by assignment (object reference).
Definition of a function
Create a new function object, encapsulate the code of the function, and assign the object to the variable name times.
>>>def times (x, y):>>> return x*y ...
Call to function
>>>x = times (2,4) >>>x8>>>x = times (' Judy ', 4) >>>x ' Judyjudyjudyjudy '
Polymorphism in Python
As seen from the above two examples, the meaning of the expression x*y in the Times function depends entirely on the object type of x and Y, the same function, which executes the multiplication in one instance and the assignment in the other instance. Python will determine the rationality of an object under a certain grammar by the object itself. This type of dependency behavior is known as polymorphism.
Example: Finding the intersection of sequences
def intersect (SEQ1, SEQ2): res = [] for x in Seq1:if x in Seq2:res.append (x) return res
or replace it with a classic list-parsing expression:
>>>[x for x in seq1 if x in SEQ2]
This single piece of code can be applied to the entire range of object types.
Python Learning: Functions (function)