谁能解释为什么将生成器作为函数的唯一位置参数传递似乎有特殊规则?
如果我们有:
>>> def f(*args):
>>> print "Success!"
>>> print args
Run Code Online (Sandbox Code Playgroud)
这正如预期的那样有效.
>>> f(1, *[2])
Success!
(1, 2)
Run Code Online (Sandbox Code Playgroud)按预期,这不起作用.
>>> f(*[2], 1)
File "<stdin>", line 1
SyntaxError: only named arguments may follow *expression
Run Code Online (Sandbox Code Playgroud)这正如预期的那样有效
>>> f(1 for x in [1], *[2])
Success!
(generator object <genexpr> at 0x7effe06bdcd0>, 2)
Run Code Online (Sandbox Code Playgroud)这有效,但我不明白为什么.不应该以与2)相同的方式失败
>>> f(*[2], 1 for x in [1])
Success!
(generator object <genexpr> at 0x7effe06bdcd0>, 2)
Run Code Online (Sandbox Code Playgroud)在__init__.py
运行文件时,导入时的行为似乎与导入时的行为不同.
如果我们有以下文件:
run.py
:
import test
Run Code Online (Sandbox Code Playgroud)
test/b.py
:
class B(object):
pass
Run Code Online (Sandbox Code Playgroud)
test/__init__.py
:
from b import B
print B
print b
Run Code Online (Sandbox Code Playgroud)
如果我们运行,__init__.py
我们会得到一个错误:
% python test/__init__.py
<class 'b.B'>
Traceback (most recent call last):
File "test/__init__.py", line 6, in <module>
print b
NameError: name 'b' is not defined
Run Code Online (Sandbox Code Playgroud)
但如果我们run.py
这样做,那么我们不会:
% python run.py
<class 'test.b.B'>
<module 'test.b' from '~/temp/test/b.py'>
Run Code Online (Sandbox Code Playgroud)
我希望这种行为是一样的.为什么这样做?
这只有在我们这样做的情况下才有效__init__.py
.要是我们:
mv __init__.py a.py
touch __init__.py
Run Code Online (Sandbox Code Playgroud)
并使run.py
:
import test.a
Run Code Online (Sandbox Code Playgroud)
然后我们得到了错误.