Date post: | 19-Dec-2015 |
Category: |
Documents |
View: | 227 times |
Download: | 1 times |
Concepts when Python retrieves a variable’s value
• Namespaces– Namespaces store information about identifiers and
the values to which they are bound– Three types
• Local, global, and built-in• They are checked by Python in that order
• Scope of a variable– The region of the program where the variable is
accessible
Namespaces
• Local namespace– Contains variables that were created in a block of code, e.g.
each function has a unique local namespace
• Global namespace– Stores the names of functions, classes, variables defined
within the file or module on outermost level
– Each module contains an identifier __name__• It holds the name of the module (“math”) or “__main__” (we’ll
see how that can be used)
• Built-in namespace– Contains functions such as raw_input, int, and range– The built-in namespace is included when the interpreter
starts (thus we automatically have access to these functions)
Namespacesbuilt_in
global
local
import math
def f(a):
x = 7
print y
x = 9
z = 13
f(z)
range, raw_input, int, float, ..
__name__ = ‘__main__’, math, f, x = 9, z = 13, ..
a = 13,
x = 7
?
def f(a):
q = 7
z = 13
f(z)
global
namespace
local namespace
z
a
q
13
7
f
built_in
global
local
import math
def f(a):
x = 7
x = 9
z = 13
f(z)
print x
range, raw_input, int, float, ..
__name__ = ‘__main__’, math, f, x = 9, z = 13, ..
a = 13,
x = 7
local x
global x
Value of x ..? 9.
local namespace
def f(a):
q = 7
z = 13
f(z)
a = 13,
q = 7
built_in
global
local
import math
def f(a):
global x
x = 7
x = 9
z = 13
f(z)
print x
range, raw_input, int, float, ..
__name__ = ‘__main__’, math, f, x = .., z = 13, ..
a = 13
global x
Value of x..? 7!
Using identifiers outside their scope
• Scope of a variable– The region of the program where the variable is
accessible
def area(r):
pi = 3.15
return pi*r*r*
a = area(1.0)
print pi
a = area(1.0)
def area(r):
pi = 3.15
return pi*r*r*
def area(r):
pi = 3.15
return pi*r*r*
a = area(1.0)
print pi
a = area(1.0)
def area(r):
pi = 3.15
return pi*r*r*
Function dir()
>>>
>>> dir()
['__builtins__', '__doc__', '__name__']
>>>
>>> print __name__
__main__
>>>
>>> x = 3
>>> dir()
['__builtins__', '__doc__', '__name__', 'x']
>>>
>>>
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError',..
.. 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'round', ..
built-in function dir() lists the identifiers in the current namespace
Since this is not a module (but rather an interactive session), the value of __name__ is __main__
dir(__builtins__) lists identifiers in the __builtins__ module
new global variable
Function help()
>>> help(range)
Help on built-in function range:
range(...)
range([start,] stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
The function help(<something>) gives you help in the interactive mode
Listing identifiers in an imported modulePython 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> >>> import math>>> dir()['__builtins__', '__doc__', '__name__', 'math']>>> >>> print math<module 'math' (built-in)>>>> >>> dir( math )['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh','e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10','modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']>>> >>> math.sqrt( 9.0 )3.0
• identifier math now points to a module
• dir(math) lists all identifiers in the math module
Importing only parts of a module
• The from/import statement– For importing only a specific part of a module– Takes identifiers from a module and inserts them
directly into the current program’s name space (avoids e.g. math. prefix)
>>> from math import sqrt>>>>>> dir()['__builtins__', '__doc__', '__name__', 'sqrt']>>>>>> sqrt( 9.0 )3.0>>>>>> from math import sin, cos, tan>>>>>> dir()['__builtins__', '__doc__', '__name__', 'cos', 'sin', 'sqrt', 'tan']
Now directly a part of the current namespace
Directly importing all identifiers from a module
>>> from math import *>>>>>> dir()['__builtins__', '__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp','log', 'log10', 'modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
Danger! If you already have a log() function with a different purpose (perhaps you are a captain and wrote the function to access the log of your spaceship..), it will be shadowed!
Either just import math and use math.log(), or ..
Binding new names to modules and module functions
• from <module> import <name> as <newname>– imports a function but gives it a different name:
from math import log as logarithm
• You can also give a new name to an entire module:– import math as mathtoolbox
The __name__ identifier
Documentation string. Printed by help() if called on this function
This code is only executed if the file is python’ed directly, not if it is imported.
gcd_
func
tion.
py
threonine:~...ExamplePrograms% python gcd_function.pyInput first integer > 0: 39Input second integer > 0: 63The greatest common divisor of 39 and 63 is 3
threonine:~...ExamplePrograms% pythonPython 2.3.2 (#1, Nov 13 2003, 20:02:35) [GCC 3.3.1] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import gcd_function as gcd_module>>> >>> print gcd_module.gcd( 39, 63)3>>>
Executing file directly:
Importing file:
Default Arguments
A function may sometimes be called repeatedly
with the same values
– When this is true default arguments can be set• Must appear to the right of any other arguments in the function
definition’s argument list:
def myfunction( a, b = 2, c = 3 ):• Given values are ‘filled in from the left’ (resolves ambiguity)
myfunction(6, 3) # set a and b, use default for c
myfunction(6) # set a, use default for b and c
– A default value can also be overridden:
myfunction(6, 3, 7) # overrides default c value
def boxVolume( length = 3, width = 2, height = 1 ):
return length * width * height
print "The default box volume is:", boxVolume()
print "\nThe volume of a box with length 10,"
print "width 2 and height 1 is:", boxVolume( 10 )
print "\nThe volume of a box with length 10,"
print "width 5 and height 1 is:", boxVolume( 10, 5 )
print "\nThe volume of a box with length 10,"
print "width 5 and height 2 is:", boxVolume( 10, 5, 2 )
The default box volume is: 6 The volume of a box with length 10, width 2 and height 1 is: 20 The volume of a box with length 10, width 5 and height 1 is: 50 The volume of a box with length 10, width 5 and height 2 is: 100
All default values used
The 10 will replace the 3 and the other default values will be used
No default values used
Here two values are sent replacing the two left-most default values
Keyword Arguments
• Keyword arguments– You can use argument names as keywords:– Allows arguments to be passed in any order as long as
they are explicitly stated:
def myfunction( a = 2, b = 3 ):
..
myfunction ( b = 5, a = 9 )
– Will use default values for those arguments that were
not given by keyword:
myfunction ( b = 5 ) # use a=2
Personal data: George, 53, president (US)
Personal data: Tony, 53, prime minister (GB)
Personal data: Ronald, 92, president (US)
name can be used as keyword as well, even though it doesn’t have a default value
Some of the arguments have default values
The arguments are given new values except age which uses the default. Values need not be entered in order.
Sets first argument, uses the defaults for all the others
How not to use keyword arguments
>>>>>> def test( name, age = 10, town = “Canberra” ):... pass...>>> test( age = 30, “Alice" )SyntaxError: non-keyword arg after keyword arg>>>>>>>>> test( age = 30 )Traceback (most recent call last): File "<stdin>", line 1, in ?TypeError: test() takes at least 1 non-keyword argument (0 given)
Keyword arguments must appear to the right of any other arguments in a function call. Otherwise ambiguity may arise.
Is “Alice” the value for name or town?
No value given for name which doesn’t have a default value