Python functions-function creation, and function properties and function arguments __ functions

Source: Internet
Author: User
Tags function definition generator shallow copy

http://blog.csdn.net/pipisorry/article/details/39123103
Creation of Functions

What happens when we define a function in Python.

The keyword DEF has two functions: it creates a function object and assigns the function object to a variable (that is, our function name). properties of a function object

Python is an object-oriented language, and everything in Python is an object. Function properties are stored as a dictionary, with the key as the property name and the value as the property content.
The properties of a function can define a function property while defining a function, or you can define a function property outside of a function declaration. You can add a property to a function by using the period identifier and the direct assignment method.
The __dict__ special property of a Function object contains the properties and property values of the function object.

Print_header.category = 1 and Print_header.text = "Some info" defines two function properties. You can view function properties by print_header.__dict__. {' Category ': 1, ' text ': ' Some info '} __code__ property of a Function object

So, when we write:

def foo ():

Return "I ' m foo!"

Python creates a new function object.  In this function object, we can see the byte code, the number of bytes (that is, the number of arguments) and some other things related to the function. Most of these things exist in the __code__ property of the function object. In fact, studying __code__ is the best way to learn how Python functions work.

For example, the number of functions Foo is obtained by Foo.__code__.co_argcount, and the codewords section exists in Foo.__code__.co_code. The properties of the __code__ object are read-only, but the __code__ property itself is not. We can do a prank and do a "brain transplant" in a function:

def foo (): Return
 "I ' m foo!"

def bar (): Return
 "I ' m bar!"

foo.__code__ = bar.__code__
Now, when we run foo (), we actually run the code that is defined as bar, and then we get:
"I ' m in bar!"

This may not be the code you want to put into the actual program, but it demonstrates some of the features of the __code__ object. It is very interesting to explore _code_ objects. [Python function Brain transplants]

Del Piero Blog



parameters of the function
Self parameter

Self is defined and needs to be defined, but is automatically passed in when called.

Self's name is not a rule of death, but it is better to follow the Convention with self. Self does not have to be written as self, 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.

When inheriting, what instance is passed in, that 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 lets you thoroughly understand the meaning of self in Python] python default Parameters

The python default parameter must point to the invariant object.

Improper use of Python default parameters will also fall in the pit:

Error using Example 1

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 seems to be good:

>>> Add_end ([1, 2, 3])
[1, 2, 3, ' end ']

When you use the default parameter invocation, the first result is also true:

>>> add_end ()
[' End ']

However, when you invoke Add_end () again, the result is incorrect:

>>> add_end ()
["End", "End"]
>>> add_end () ["End", "End", "End"
]

Many beginners are puzzled that the default parameter is [], but the function seems to "remember" the list that was last added ' end ' every time. explanations for the reasons are as follows

When the Python function is defined, the value of the default parameter L is computed. That is [], because the default parameter L is also a variable, it points to the object [], each time the function is called, if the contents of L are changed, the contents of the default parameter will be changed at the next call, no longer the [] of the function definition. So, to define the default parameters, keep in mind that the default argument must point to the invariant object.

To modify the example above, we can implement the invariant object with none:

def add_end (l=none):
    if L is None:
        l = []
    l.append ("End") return
    L

Now, no matter how many times you call, there is no problem:

>>> add_end ()
[' End ']
>>> add_end ()
[' End ']

Error using example 2

Def extendlist (val, list = []):

List.append (Val)

Return list

L1 = extendlist (10)

L2 = Extendlist (123, [])

L3 = Extendlist (' a ')

Print (L1, L2, L3)

The result is [ten, ' a '], [123], [Ten, ' a ']

Correct modification:

Def extend_list (Val, List=none):

If not list:

list = []

List.append (Val)

Return list

So understand, the function default parameter value is [], as defined in the function definition, and the name list is just a pointer to the value of the default parameter at the start [].
So L1 = Extendlist (10), when no arguments are specified, the list points to and uses the default parameter value [], and the function completes the default parameter to [10],l1 point to the default parameter value;
L2 = Extendlist (123, []), given the arguments [],list point to the user given [] (note is not the default parameter []), so the L2 is very simple, that is [123];
L3 = Extendlist (' A '), with no parameters specified, the list points to and uses the default parameter value [10], and the function execution completes the default parameter to [Ten, ' a '], so L1 and L2 all point to the new value [Ten, ' a '], which is the default parameter value of the current function.
Why do you want to design a constant object such as Str and none?

Because once the invariant object is created, the data inside the object cannot be modified, thus reducing the error caused by the modification of the data.

In addition, because the object is invariant, the multitasking environment reads the object without the need for locking, while reading the problem is not. When we write a program, if we can design a invariant object, then try to design unchanged objects.

general parameters of functions and their iterative parameters

One thing to understand is that Python has "no pointers, but all objects are pointers."

Parameter passing of a Python function: Immutable type: A value transfer similar to C + +, such as integers, strings, tuples. such as fun (a), passing only the value of a, does not affect the object a itself. For example, to modify the value of a within fun (a), just modify another replicated object, without affecting the a itself. Soft type: A reference pass like C + +, such as a list, a dictionary. such as Fun (LA), is the true transmission of LA, after the modified fun outside of LA will also be affected in Python everything is an object, strict meaning we can not say value transfer or reference delivery, we should say to pass immutable objects and passing variable objects.

If the parameter is Python mutable type list,dict, and so on (with C + + arrays), the incoming equivalent is the pointer address, so the list outside the function will also change.

The python function parameter is passed if the tuple (the same C + + struct) is passed.

In the C language, we see the statement int a=8, which means that the value of an object A,a is created with an assignment of 8. If we next write an int b=a, we actually create an object B and then copy the value of a object to B, noting that the value of a corresponds to a, not a itself. If you want to obtain the address of a itself, you need to use &a.

However, in Python, the program

Import Copy
A = [1, 2, 3, 4, [' A ', ' B ']] #原始对象
b = A #赋值, passing the reference to the object
c = Copy.copy (a) #对象拷贝, shallow copy
D = copy.deepcopy (a) #对象拷贝, deep copy

As an example, you actually first create an object [1, 2, 3, 4, [' A ', ' B ']], and then assign the address of the object to a, the statement b=a, as B is an alias for a. And C is a shallow copy of the object.

#!/usr/bin/env Python3
# Coding=utf-8
def func (List1):
List1 = [1]
List2 = [1,2,3]
Func (List2)
Print (LIST2)

[1,2,3,1] Leather Blog



variable Parameters
positional parameters: variable parameters

In a Python function, you can also define variable parameters. As the name suggests, the variable parameter is the number of parameters passed in is variable, can be one, 2 to any, or 0.

We take the mathematics titled example, given a set of numbers a,b,c ..., please compute A2 + b2 + C2 + ....

To define this function, we must determine the input parameters. Because the number of parameters is not certain, we first think that we can put a,b,c ... 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 called, you need to assemble a list or tuple:>>> calc ([1, 2, 3]) to change the parameter of the function to a variable parameter

Def calc (*numbers):
    sum = 0 for
    n in numbers:
        sum = SUM + N * n * return
    sum

When you define a variable parameter and define a list or tuple parameter, you simply add a * number to the parameter. 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 of the arguments, including 0 parameters:

>>> Calc (1, 2)
>>> Calc ()

If you already have a list or tuple, what to do if you want to invoke a variable parameter. You can do this:

>>> nums = [1, 2, 3]
>>> Calc (nums[0], nums[1], nums[2])
14
Using * for Deconstruction

This kind of writing is certainly feasible, the problem is too cumbersome, so python allows you to add a * number in front of the list or tuple, passing the list or tuple elements into variable parameters (rather than just as a list parameter): The walk takes an array and uses it in band For deconstruction. However, it should be noted that the indefinite length of the parameter args when passed to the function, you need to first convert infinitesimal group tuple. This means that if you take a generator as a parameter into a function, the generator will iterate through it and convert it to a tuple. This can consume a lot of memory

>>> nums = [1, 2, 3]
>>> calc (*nums)
14
keyword Parameters

Keyword parameters to improve code readability
You can provide a default value to a function by using a keyword parameter
Easy to expand function parameters

Variable parameters allow you to pass in 0 or any of the parameters, which are automatically assembled as a tuple when the function is called. The keyword parameter allows you to pass in 0 or any parameter with a parameter name, which is automatically assembled into a dict within the function. Take a look at the example:

def person (name, age, **kw):
    print ' name: ', Name, ' Age: ', age, ' other: ', kw

The function person accepts the keyword parameter kw in addition to the required parameter name and age. When you call the function, you can pass in only the required parameters, or you can pass in any number of keyword parameters:

>>> person (' Bob ', "city= ' Beijing ')
name:bob age:35 Other: {" City ": ' Beijing '}
>>> person ( ' Adam ', gender= ' m ', job= ' Engineer ')
Name:adam age:45 Other: {' Gender ': ' m ', ' job ': ' Engineer '}
functional Examples of keyword parameter extension functions

For example, in the person function we are guaranteed to receive both the name and age parameters, but we can also receive it if the caller is willing to provide more arguments. Imagine you are doing a user registration function, in addition to user name and age is required, the other is optional, the use of 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 to a keyword parameter:

>>> kw = {' City ': ' Beijing ', ' Jobs ': ' Engineer '}
>>> person (' Jack ', city=kw[' city '], job=kw[' Job '])
name:jack age:24: {' City ': ' Beijing ', ' job ': ' Engineer '}

Of course, the complex calls above can be written in simplified notation:

>>> kw = {' City ': ' Beijing ', ' job ': ' Engineer '}
>>> person (' Jack ', **kw)
name:jack age:24 Other: {' City ': ' Beijing ', ' job ': ' Engineer '}
to define a function that can use only keyword parameters

Normal way, when called without forcing the use of keyword parameters

how to enforce keyword parameters in Python3
# defines a method that is used 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]
# that's doable.
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 no keyword parameter is specified and an error is given
Get_indexs (array, 1, True)
# Typeerror:get_indexs () takes 1 positional argument but 3 were given

how to enforce keyword parameters in Python2

# defines a method that is used to traverse an array to find the index of the target element equal to (or not equal to)
# using **kwargs, which represents the receive keyword parameter, the Kwargs within the function is a dictionary, and the incoming keyword parameter exists as a key-value pair.
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]
# that's doable.
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 no keyword parameter is specified and an error is given
Get_indexs (array, 1, True)
# Typeerror:get_indexs () takes 1 positional argument but 3 were given
parameter Combinations

To define a function in Python, you can use the required parameters, default parameters, variable parameters, and keyword parameters, all of which can be used together, or use only some of these 4 parameters.

Note that the order of the parameter definitions must be: required, default, variable, and key parameters.

For example, define a function that contains the 4 parameters mentioned above:

def func (A, B, c=0, *args, **kw):
    print ' A = ', A, ' B = ', B, ' C = ', C, ' args = ', args, ' kw = ', kw

When the function is called, the Python interpreter automatically passes the corresponding arguments in the parameter position and the argument name.

>>> func (1, 2)
a = 1 b = 2 c = 0 args = () kw = {}
>>> func (1, 2, c=3)
a = 1 b = 2 c = 3 arg s = () kw = {}
>>> func (1, 2, 3, ' A ', ' B ')
a = 1 b = 2 c = 3 args = (' A ', ' b ') kw = {}
>>> F UNC (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 you can call the function through a tuple and dict:

>>> args = (1, 2, 3, 4)
>>> kw = {' X ':}
>>> func (*args, **kw)
a = 1 b = 2 c = 3 args = (4,) kw = {' X ': 99}

Therefore, for any function, it can be invoked in the form of a similar func (*args, **kw), regardless of how its parameters are defined.

from:http://blog.csdn.net/pipisorry/article/details/39123103

Ref: [Parameters of Function]


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.