Skip to main content
 首页 » 编程设计

python之在方法内的 %time 语句中定义的变量在该语句之后不可访问

2024年10月17日9hnrainll

这似乎工作正常 -

%time a = "abc" 
print(a) 
 
CPU times: user 0 ns, sys: 0 ns, total: 0 ns 
Wall time: 19.1 µs 
abc 

这不是——

def func(): 
    %time b = "abc" 
    print(b) 
 
func() 
 
CPU times: user 0 ns, sys: 0 ns, total: 0 ns 
Wall time: 31 µs 
--------------------------------------------------------------------------- 
NameError                                 Traceback (most recent call last) 
<ipython-input-8-57f7d48952b8> in <module>() 
      3     print(b) 
      4  
----> 5 func() 
 
<ipython-input-8-57f7d48952b8> in func() 
      1 def func(): 
      2     get_ipython().magic(u'time b = "abc"') 
----> 3     print(b) 
      4  
      5 func() 
 
NameError: global name 'b' is not defined 

这是一个指向 notebook 的链接

我正在使用 python 2.7,还没有用 python3 尝试过。

这是预期的行为吗?

请您参考如下方法:

我几乎可以肯定这是一个 IPython 错误。 Reported here .

In [31]: def func(): 
    ...:     a = 2 
    ...:     %time b = 1 
    ...:     print(locals()) 
    ...:     print a 
    ...:     print b 
 
In [32]: func() 
CPU times: user 3 µs, sys: 0 ns, total: 3 µs 
Wall time: 6.2 µs 
{'a': 2, 'b': 1} 
2 
--------------------------------------------------------------------------- 
NameError                                 Traceback (most recent call last) 
<ipython-input-32-08a2da4138f6> in <module>() 
----> 1 func() 
 
<ipython-input-31-13da62c18a7e> in func() 
      4     print(locals()) 
      5     print a 
----> 6     print b 
      7 
      8 
 
NameError: global name 'b' is not defined