http://blog.csdn.net/pipisorry/article/details/39123103
Self parameter
Self is defined when it is defined, but is automatically passed in when it is called.
Self's name is not a rule of death, but it is best to use self as agreed. Self does not have to be written as self, it can be any character.
Self always refers to an instance of the class at the time of invocation. Self represents an instance of a class, not a class.
In inheritance, which instance is passed in, which is the incoming instance, not the instance of the class that defines self.
In a descriptor class, self refers to an instance of a descriptor class.
[ an article that gives you a thorough understanding of the meaning of self in Python]
The python default parameter must point to the immutable object
Python default parameters are useful, but improper use will also fall into the pit:
First define a function, pass in a list, add an END and return:
def add_end (l=[]): l.append (' End ') return L
When you call normally, the result looks good:
>>> Add_end ([1, 2, 3]) [1, 2, 3, ' end ']
When you use the default parameter call, the result is also right at the beginning:
>>> add_end () [' End ']
However, when you call add_end () again, the result is incorrect:
>>> add_end () [' End ', ' End ']>>> add_end () [' End ', ' End ', ' end ']
Many beginners are puzzled, the default parameter is [], but the function seems to "remember" the last time the " END " after the list.
The reasons are explained as follows:
When the Python function is defined, the default parameterLThe value is calculated, i.e.[], because the default parameterLis also a variable that points to an object[], each time you call the function, if you change theL, the contents of the default parameter change the next time the call is made, no longer the function definition[]The So, one thing to keep in mind when defining default parameters: The default parameter must point to the immutable object!
To modify the above example, we can use the none of the immutable object to achieve:
def add_end (l=none): if L is None: l = [] l.append (' End ') return L
Now, no matter how many times it is called, there is no problem:
>>> add_end () [' End ']>>> add_end () [' End ']
Why design an immutable object such as Str and none?
Since immutable objects are created, the data inside the object cannot be modified, which reduces the error caused by modifying the data. In addition, because the object is not changed, the simultaneous reading of objects in a multitasking environment does not require locking, while reading a little bit of a problem. When we are writing a program, if we can design a constant object, we try to design it as an immutable object.
Phi Blog
Positional parameters: Variable parameters
In the Python function, you can also define mutable parameters. As the name implies, the variable parameter is the number of parameters passed in is variable, can be one, 2 to any, or 0.
We take the math titled example, given a set of numbers a,b,c ..., please calculate a2 + b2 + C2 + ....
To define this function, we must determine the input parameters. As the number of arguments is uncertain, we first think that we can put a,b,c ... Passed in as a list or tuple, so that the function can be defined as follows:
def calc (numbers): sum = 0 for n in numbers: sum = SUM + N * n return sum
But when calling, you need to assemble a list or a tuple:>>> Calc ([1, 2, 3])
Change the parameter of a function to a variable parameter
Def calc (*numbers): sum = 0 for n in numbers: sum = SUM + N * n return sum
When you define a mutable parameter and define a list or tuple parameter, just precede the parameter with an * number. Inside the function, the parameter numbers receives a tuple, so the function code is completely unchanged. However, when you call the function, you can pass in any parameter, including 0 parameters:
>>> Calc (1, 2) >>> calc ()
What if you have a list or a tuple and you want to invoke a mutable parameter? You can do this:
>>> nums = [1, 2, 3]>>> Calc (nums[0], nums[1], nums[2]) 14
Use * to deconstruct
This kind of writing is of course feasible, the problem is too cumbersome, so python allows you to precede the list or tuple with an * number, the list or a tuple of elements into a mutable parameter (rather than just as a list parameter): Go to take an array into, use in the When used * To be deconstructed. It is important to note, however, that the variable-length parameter, args, is passed to the function, and the Narimoto group of tuples needs to be converted first. This means that if you take a generator as a parameter into a function, the generator will go through it and convert it to a tuple. This can consume a lot of memory
>>> nums = [1, 2, 3]>>> Calc (*nums) 14
Phi Blog
Keyword parameters
Keyword parameters to improve code readability
You can give a default value to a function by using the keyword argument
Easy to expand function parameters
Variable parameters allow you to pass in 0 or any of the parameters that are automatically assembled as a tuple when the function is called. The keyword parameter allows you to pass in 0 or any parameter with parameter names that are automatically assembled inside the function as a dict. Take a look at the example:
def person (name, age, **kw): print ' name: ', Name, ' Age: ', age, ' other: ', kw
Function PersonIn addition to the required parametersnameAnd AgeAlso accepts the keyword parameterkw。 When you call this function, you can pass in only the required parameters,You can also pass in any number of keyword parameters:
>>> person (' Bob ', +, city= ' Beijing ') Name:bob age:35 other: {"City": ' Beijing '}>>> person (' Adam ', 45, Gender= ' m ', job= ' Engineer ') Name:adam age:45 Other: {' Gender ': ' m ', ' job ': ' Engineer '}
function examples for keyword parameter extension functions
For example, in the person function, we are guaranteed to receive both the name and the age parameters, but we can receive them if the caller is willing to provide more arguments. Imagine you are doing a user registration function, in addition to the user name and age is required, the other is optional, using the keyword parameters to define this function can meet the requirements of registration.
Similar to variable parameters, you can also assemble a dict, and then convert the dict into a keyword parameter:
>>> kw = {' City ': ' Beijing ', ' Jobs ': ' Engineer '}>>> person (' Jack ', ' city=kw[' city ', job=kw[' job ') Name:jack age:24 Other: {' City ': ' Beijing ', ' job ': ' Engineer '}
Of course, the above complex invocation can be simplified:
>>> kw = {' City ': ' Beijing ', ' job ': ' Engineer '}>>> person (' Jack ', ' **kw ') name: Jack age:24 Other: {' City ': ' Beijing ', ' job ': ' Engineer '}
Define a function that can use only keyword parameters
Normal way, the use of keyword arguments is not enforced at the time of invocation
How to use the Force keyword parameter in Python3
# defines a method whose function is to traverse an array to find the index of the target element equal to (or not equal to)
def get_indexs (Array, *, target= ", judge=true):
For index, item in enumerate (array):
If judge and item = = target:
Yield index
Elif not judge and item! = target:
Yield index
Array = [1, 2, 3, 4, 1]
# It works
result = Get_indexs (array, target=1, judge=true)
Print (list result) # [0, 4]
# you can also ignore parameters that have default values
result = Get_indexs (array, target=1)
Print (list result) # [0, 4]
# but do not specify the keyword parameter to error
Get_indexs (array, 1, True)
# Typeerror:get_indexs () takes 1 positional argument but 3 were given
How to use the Force keyword parameter in Python2
# defines a method whose function is to iterate through an array to find the index
# of the target element equal to (or not equal to) using **kwargs, representing the Receive keyword argument, the Kwargs in the function is a dictionary, and the passed-in keyword argument exists as a key-value pair in the form of
def get_indexs (Array, **kwargs):
target = kwargs.pop (' target ', ')
judge = Kwargs.pop (' Judge ', True)
for index, item in enumerate (array):
if judge and item = = target:
Yield index
elif not judge and item! = target:
yield index
Array = [1, 2, 3, 4, 1]
# This is possible
result = g Et_indexs (Array, target=1, judge=true)
Print (list result) # [0, 4]
# can also ignore parameters with default values
result = Get_indexs (array, Target=1)
Print (list result) # [0, 4]
# But do not specify a keyword parameter error
Get_indexs (array, 1, True)
# Typeerror:get_indexs () Takes 1 positional argument but 3 were given
Phi Blog
parameter Combinations
In Python, you define functions that can be used with required parameters, default parameters, variable parameters, and keyword parameters, or only some of these 4 parameters.
Note that the order of the parameter definitions must be: required, default, variable, and keyword parameters.
For example, define a function that contains the above 4 parameters:
def func (A, B, c=0, *args, **kw): print ' A = ', A, ' B = ', B, ' C = ', C, ' args = ', args, ' kw = ', kw
At the time of the function call, the Python interpreter automatically passes the corresponding parameters according to the parameter location and argument name.
>>> func (1, 2) A = 1 b = 2 c = 0 args = () kw = {}>>> func (1, 2, c=3) A = 1 b = 2 c = 3 args = () kw = {}& gt;>> func (1, 2, 3, ' A ', ' B ') A = 1 b = 2 c = 3 args = (' A ', ' b ') kw = {}>>> func (1, 2, 3, ' A ', ' B ', x=99) a = 1 b = 2 c = 3 args = (' A ', ' b ') kw = {' X ': 99}
The most amazing thing is that through a tuple and dict, you can also call the function:
>>> args = (1, 2, 3, 4) >>> kw = {' X ': 99}>>> func (*args, **kw) A = 1 b = 2 c = 3 args = (4,) kw = {' X ': 99}
So, for any function, it can be called by the form of a func (*args, **kw) , regardless of how its arguments are defined.
from:http://blog.csdn.net/pipisorry/article/details/39123103
Ref: [Parameter of function]
Python functions-arguments to functions