Python function Learning Notes

Source: Internet
Author: User
Local name Static detection
When Python probes local scopes: It is detected when Python compiles code, not through their assignment at run time.
Under normal circumstances, names that are not duplicated in the function are looked up in the module that contains it:
>>> x=99
>>> def selector ():
... print X
...
>>> selector ()
99
But:
>>> def selector ():
... print X
... x=100
...
>>> selector ()
Traceback (most recent):
File " ", line 1, in?
File " ", line 2, in selector
unboundlocalerror:local variable ' x ' referenced before assignment
An undefined name error will be obtained.
When interactive input or import from a module, Python reads and compiles the code, and when compiled, Python looks at the assignment of X and decides that x will be a local name anywhere in the function. By the time the function actually runs and print executes, the assignment hasn't happened, and Python says you're using an undefined name. According to the rules of his name, it should be that the local x was used before the assignment.
Workaround:
If you want to print global X, you should declare it in the global statement: (This means that the assignment also changes the global X, not the local x)
>>> def selector ():
... global X
... print X
... x=88
...
>>> selector ()
99
If you want to print out a global assignment, in the set a local, import the module containing it and qualify for this global version:
>>> x=99
>>> def selector ():
... import __main__
... print __main__.x
... x=88
... print X
...
>>> selector ()
99
88
The qualification (. x part) obtains a value from a Namespace object. The namespace of the interactive environment is a module called __main__.
Nested functions can be nested scopes (different in new versions and older versions)
>>> def outer (x):
... def inner (i):
... print I,
... if I:inner (i-1)
... inner (x)
...
>>> Outer (3)
3 2 1 0
Saving references with default values
>>> def outer (x):
... def inner (i,self=inner):
... print I,
... if I:self (i-1)
... inner (x)
...
>>> Outer (3)
Traceback (most recent):
File " ", line 1, in?
File " ", line 2, in outer
Unboundlocalerror:local variable ' inner ' referenced before assignment
Resolution principle: The simplest way is always the most correct way
>>> def inner (i):
... print I,
... if I:inner (i-1)
...
>>> def outer (x):
... inner (x)
...
>>> Outer (3)
3 2 1 0
The default Mutable object
>>> def saver (x=[]):
... x.append (1)
... print X
...
>>> Saver ([2])
[2, 1]
>>> Saver ()
[1]
>>> Saver ()
[1, 1]
>>> Saver ()
[1, 1, 1]
The problem is that there is only one list object that is generated when--def executes. When each function is called, you do not get the new list object, but the growth of the original list object.
Workaround: If that is not the behavior you want, simply move the default value into the function body. As long as the values in the code are executed every time the function runs, you will get a new object each time:
>>> def saver (x=none):
... if X is None:
... x=[]
... x.append (1)
... print X
...
>>> Saver ([2])
[2, 1]
>>> Saver ()
[1]
>>> Saver ()
[1]
>>> Saver ()
[1]
The If statement above can be substituted for almost x=x or [], because Python or will return one of his operands: If no argument is passed, x defaults to None, so or returns a generated empty list on the right. But this is not exactly the same, when you pass an empty list, the function expands and returns a newly generated list instead of extending to the previous version and returning a passed list (the expression becomes [] or [], which calculates the new list)
  • 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.