Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- __author__ = 'Neys'
- """
- Create a function add(n) which returns a function that always adds n to any number
- addOne = add(1)
- addOne(3) # 4
- addThree = add(3)
- addThree(3) # 6
- """
- # Question is about the principles of closure. AKA a technique for implementing lexically scoped name binding.
- """Lexical scoping: Use of local variables. Local means variables with limited scope, that only exist within a specific
- function. Helps avoid name collision between 2 identically named variables.
- So what does it mean to be within a function? If a variable is within the scope of a certain function then its scope
- is effectively the block of code following the function definition. In that block the variable name exists, and is bound
- to an assigned value. Outside the block the variable name does not exist.
- Dynamic Scoping:
- If the variable name's scope is in a certain function, then it's scope is the time frame with which the function is
- executing. (While function is running the variable name exists and is bound to a value.) After the function returns the
- variable name does not exist. """
- pi = 3.1415 # create variable pi in global scope
- pi_holder = None
- def create_area():
- pi_holder = pi # local variable, different from pi_holder outside
- def area(r):
- return pi_holder*r*r
- return area # area() gives error
- area = create_area()
- print("area(10) = ", area(10))
- del pi_holder # delete global pi_holder w/o mutating local lexical pi_holder
- try:
- pi_holder # proves pi_holder is created and removed within scope of create_area() and is local to area(r)
- except NameError:
- print("pi_holder is empty")
- print("area(100) = ", area(100))
- x = 42
- def local_var_test():
- temp = x # correct variable assignment
- print("LHS temp assignment to global variable x = ",temp) # 42
- # x = temp # incorrect because x is referenced before assignment to local scope of x
- # print(x) # incorrect also
- n = None # define n
- def add(n=n): # n is what it is arg passed upon function
- def add_to_n(k):
- return k + n
- return add_to_n
- addOne = add(1)
- addTwo = add(2)
- addZero= add(0)
- print(addZero(7))
- # Final Solution!
- def add(n):
- def add_to_x(x):
- return x + n
- return add_to_x
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement