您如何知道变量是否已在运行时在代码中的特定位置设置?这并不总是显而易见的,因为(1)变量可以有条件地设置,(2)变量可以有条件地删除.我正在寻找像defined()Perl isset(),PHP或defined?Ruby中的东西.
if condition:
a = 42
# is "a" defined here?
if other_condition:
del a
# is "a" defined here?
Run Code Online (Sandbox Code Playgroud) 给出以下代码:
def A() :
b = 1
def B() :
# I can access 'b' from here.
print( b )
# But can i modify 'b' here? 'global' and assignment will not work.
B()
A()
Run Code Online (Sandbox Code Playgroud)
对于B()函数变量中的代码,b在外部作用域中,但不在全局作用域中.是否可以b从B()函数内修改变量?当然我可以从这里读取它print(),但是如何修改呢?
我有这样的代码(简化):
def outer():
ctr = 0
def inner():
ctr += 1
inner()
Run Code Online (Sandbox Code Playgroud)
但是ctr会导致错误:
Traceback (most recent call last):
File "foo.py", line 9, in <module>
outer()
File "foo.py", line 7, in outer
inner()
File "foo.py", line 5, in inner
ctr += 1
UnboundLocalError: local variable 'ctr' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
我怎样才能解决这个问题?我认为嵌套的范围可以让我这样做.我试过'全球',但它仍然无效.
Is it "good practice" to create a class like the one below that can handle the memoization process for you? The benefits of memoization are so great (in some cases, like this one, where it drops from 501003 to 1507 function calls and from 1.409 to 0.006 seconds of CPU time on my computer) that it seems a class like this would be useful.
However, I've read only negative comments on the usage of eval(). Is this usage of …
在python中,我可以写:
def func():
x = 1
print x
x+=1
def _func():
print x
return _func
test = func()
test()
Run Code Online (Sandbox Code Playgroud)
当我运行它时,输出是:
1
2
由于_func可以访问func中定义的"x"变量.对...
但如果我这样做:
def func():
x = 1
print x
def _func():
x+=1
print x
return _func
test = func()
test()
Run Code Online (Sandbox Code Playgroud)
然后我收到一条错误消息:UnboundLocalError:在赋值之前引用的局部变量'x'
在这种情况下,似乎_func不能"看到""x"变量
问题是:为什么在第一个例子中打印x"看到""x"变量,而数学运算符x + = 1抛出异常?
我不明白为什么......