我知道自从我发现 python 以不同的方式对待这个命名空间
def foo(l=[]):
l.append(1)
print(l)
foo()
foo()
foo([])
foo()
Run Code Online (Sandbox Code Playgroud)
打印以下内容。
[1]
[1,1]
[1]
[1,1,1]
Run Code Online (Sandbox Code Playgroud)
所以我对它们用作对象初始值设定项持怀疑态度。最近我遇到了另一个类似的奇怪行为,如下所示。
class Foo:
bar = 0
def __init__(self):
self.a = bar
Foo()
Run Code Online (Sandbox Code Playgroud)
这会引发异常,因为bar该命名空间内未定义。
class Foo:
bar = 0
def __init__(self, a=bar)
self.a = a
Foo()
Run Code Online (Sandbox Code Playgroud)
现在,这成功地将类变量持有的值分配给初始化器内的foo对象。a为什么会发生这些事情以及如何处理默认参数值?
我认为这应该工作:
file = open('filename.ppm', 'wb')
file.write('upper\nlower'.encode(encoding='ascii'))
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,虽然没有换行符;filename.pmm使用记事本打开时,其中包含“ upperlower”。