Created
April 28, 2014 08:51
-
-
Save dchentech/11365960 to your computer and use it in GitHub Desktop.
python closure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def computer(): | |
count = 5 | |
def plus(num): | |
count += num | |
print count | |
return plus | |
plus = computer() | |
plus(3) | |
plus(5) | |
""" | |
Traceback (most recent call last): | |
File "closure.py", line 8, in <module> | |
plus(3) | |
File "closure.py", line 4, in plus | |
count += num | |
UnboundLocalError: local variable 'count' referenced before assignment | |
""" | |
class Hello(): | |
@classmethod | |
def computer(cls): | |
count = 5 | |
def plus(num): | |
# or count += num | |
v = count + num | |
count = v | |
print count | |
return plus | |
plus = Hello.computer() | |
plus(3) | |
plus(4) | |
""" | |
Traceback (most recent call last): | |
File "closure.py", line 12, in <module> | |
plus(3) | |
File "closure.py", line 6, in plus | |
v = count + num | |
UnboundLocalError: local variable 'count' referenced before assignment | |
""" | |
class Hello(): | |
@classmethod | |
def computer(cls): | |
count = 5 | |
def plus(num): | |
print count + num | |
return plus | |
plus = Hello.computer() | |
plus(3) | |
plus(4) | |
""" | |
8 | |
9 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment