9 python
此代码生成错误消息,我发现这令人惊讶:
class Foo(object):
custom = 1
def __init__(self, custom=Foo.custom):
self._custom = custom
x = Foo()
Run Code Online (Sandbox Code Playgroud)
任何人都可以提供启发吗?
Ric*_*dle 11
这Foo是不可见的,因为你正在构建它.但由于你的范围相同custom,你可以说custom而不是Foo.custom:
class Foo(object):
custom = 1
def __init__(self, mycustom=custom):
self._custom = mycustom
Run Code Online (Sandbox Code Playgroud)
但请注意,Foo.custom稍后更改不会影响custom随后创建的Foos 的值,请参阅:
class Foo(object):
custom = 1
def __init__(self, mycustom=custom):
self._custom = mycustom
one = Foo()
Foo.custom = 2
two = Foo()
print (two._custom) # Prints 1
Run Code Online (Sandbox Code Playgroud)
通过使用哨兵默认值,您可以得到您想要的:
class Foo(object):
custom = 1
def __init__(self, mycustom=None):
if mycustom is None:
self._custom = Foo.custom
else:
self._custom = mycustom
one = Foo()
Foo.custom = 2
two = Foo()
print (two._custom) # Prints 2
Run Code Online (Sandbox Code Playgroud)
我们做的是以下
class Foo( object ):
custom = 1
def __init__( self, arg=None )
self._custom = self.custom if arg is None else arg
Run Code Online (Sandbox Code Playgroud)
这绕过了名称是否Foo已被定义的令人困惑的问题.
| 归档时间: |
|
| 查看次数: |
4947 次 |
| 最近记录: |