Don't want to be a lamb to be slaughtered!!!! To become strong ....
The definition and use of functions in the front or for a reason, now the language tends to general, basic types are basically those, focus on the use of learning objects, and the most fundamental is the use of methods, so the first introduction, the purpose of the method is to reuse and encapsulation
I. Definition of a method
The definition of the method is defined using the keyword Def, which defines the following format:
def method Name (parameter definition): method Body
- Method Name: The specification of the method name is the same as the variable name specification
- Parameter definition: More complex, will be explained later
- Colon: This is similar to Java {}, essential
- Method Body: The functions implemented by the method are defined here
A simple example:
# define SayHello def SayHello (): Print ('hello yiwangzhibujian') # Call Method SayHello ()
The basic usage is still very simple, and it is not difficult to get into it.
Second, the return value of the method
The return value of the keyword uses return, in general, all methods have a return value, if the method does not use return, then Python will be added at the end of the code: return None
The return value is used in the same way as the Java language to return results or to end prematurely, but there are some different places
2.1 Returning multiple results
This is a special function, you can return multiple values, actually return a tuple, the use of the return value and the use of a tuple is the same, a simple example is as follows:
def Returnmulti (): return ,returnmultiresult= print (result)print( Isinstance (result, tuple))======== console output ========(1, 2, 3) True
So when defining a function, write a comment that lets the user know exactly what type of return value it is.
2.2 Return function
In addition to being able to return a value, you can return a function because the function is also a variable. The feeling is exactly the same as JS.
Iii. parameters of the method
The method parameters are much more, besides the basic usage, others need to be mastered well.
3.1 Overloading of methods
Because the parameter does not have the type, so Python's function overload cannot depend on the parameter type, but only by the number of parameters, this is still a headache, the type needs to be judged in the method body.
3.2 Parameter Default value
If you need to pass in more than one parameter, you can set this value to the default value if the value of the parameter is used very frequently, so it is easy to use.
For example, a string converts a global function of a number: int ()
- Definition of a parameter: Int (x=0)
- Two parameter definitions: int (x, base=10)
When there is only one parameter, there is a default value of 0, even if not entered:
Print (int ())) Print (int (0)) Print (Int ('0'))
So the above three outputs are all 0.
Of course, the general string to the number is a decimal, so the 10 as the default of the system, of course, if you need to convert the binary, you can set parameters, which need to be actively set up:
Print (Int ('ten')) Print (Int ('ten', base=10)) Print (Int ('ten', base=2))========= console output =========10102
This is the basic usage of the default value, but one thing to note is that the default parameter defaults must be placed after the normal parameter.
3.3 Variable Parameters
Variable parameters and Java variable parameters are the same, used to represent the same processing of the number of indeterminate parameters, but the expression is not the same, the following example method to print the actual incoming method parameters, the implementation can be based on the actual situation:
def See (*nums): print(nums) print(isinstance (Nums, Tuple) See (All-in-one)========= console output =========(1, 2, 3) True
As a matter of fact, mutable parameters are actually passed in as a tuple to the inside of the method. There are also a few things to note about using mutable parameters:
- A method can have only one variable parameter
- The variable parameter must be placed after the default parameter
3.4 Keyword Parameters
A mutable parameter has its drawbacks, which is that it can only be used for multiple values of the same element, but not for each value type, but when you need to distinguish it, you need to use the keyword parameter, which can be passed along with the name of the parameter:
def See (* *keyvalue) :print(keyvalue )print(isinstance ( KeyValue, Dict)) See (a=1,b=2,c=3)======= Console output ======={'a' ' b ' ' C ': 3}true
As you can see, Python actually encapsulates the keyword parameter into a dict and passes it into the method so that it can be used when you have it, and you can use it when you have the need.
The input of the keyword parameter can also be restricted, using the * partition, followed by the qualified input name:
def info (name,age,*, country,city): print(name,age,country,city) info ( ' Yiwangzhibujian ', 27,country='Chine', city='Beijing' )========= console output ===========Chine Beijing
Of course, if the keyword parameter specifies the desired parameter value, but does not have the input, it will still be an error, so you can also add the default value of the keyword parameter:
def info (name,age,*,country= ' China', City): print(name,age,country,city)
If there is already a mutable parameter in the function definition, then the named keyword argument that follows will no longer require a special delimiter *, for example:
def person (name, age, *favonum, Country, City): Print(name, age, Favonum, country, city)
The above basic usage can be mastered.
3.5 mixing of various types of parameters
Parameter type more, how to use it is a headache, the order is wrong. The order is as follows: normal parameter, default parameter, variable parameter, keyword parameter.
Iv. other applications of Functions 4.1 null function
When we define a parameter, if we have not thought how to implement it, the empty word will be error, this time can use pass to represent the empty function:
def Me (): Pass
In this way, the operation will not be error, and so on later want to realize to add.
4.2 Parameter type checking
Because Python is not a strongly typed language, the type of the parameter is not deterministic, but when we assume its type and use it in a situation where the argument type is indeterminate, an exception is thrown, so it is necessary to type-check the incoming arguments, and when the parameters of the passed-in error can be effectively alerted, Parameter type checking uses the previously mentioned global function isinstance (), the function of the specific use of methods described: Java Programmer Learning Python (four)-built-in methods and built-in variables in the Isinstance ().
4.3 Incoming functions
Now that the function is an object, Python is also allowed to pass in a method. For example, define a judgment method:
def judge (fun,*num): return fun (num)print(judge (max,1,2,3)) Print(judge (min,1,2,3))========== console output ===========31
This will be based on the incoming method to obtain the specified number, of course, the parameter type check is necessary, otherwise, a function is not a parameter call method will definitely error.
4.4 Description of methods in documents
In the process of learning Python is often to read the document, about the document in the description of the function of a simple introduction, first you have to master the above several types of parameters, which is the basic requirements. There is also the understanding of the brackets:
For example: Str.endswith (suffix[, start[, end]), the brackets indicate that the parameters can be selected for input, not required, of course, the choice also represents a default value, note the definition of the function, that is, this function can be entered as:
Str.endswith (suffix) str.endswith (suffix, start) str.endswith (suffix, start, end)
This understanding can not be defined when the function is actually defined.
4.5 In-depth understanding of functions
function is also an object similar to JS, the method name is just a reference to the function object, this feature will have the following effect:
Print (ABS ( -1)) ABS2=ABSprint(ABS2 (-1))
This is only a basic understanding, after the subsequent study of the understanding will be added.
"Python" Java Programmer learns Python (v)-definition and use of functions