【发布时间】:2009-07-01 21:25:34
【问题描述】:
这段代码产生了一条错误消息,我觉得很奇怪:
class Foo(object):
custom = 1
def __init__(self, custom=Foo.custom):
self._custom = custom
x = Foo()
谁能给点启示?
【问题讨论】:
标签: python
这段代码产生了一条错误消息,我觉得很奇怪:
class Foo(object):
custom = 1
def __init__(self, custom=Foo.custom):
self._custom = custom
x = Foo()
谁能给点启示?
【问题讨论】:
标签: python
Foo 不可见,因为您正在构建它。但是由于你和custom在同一个范围内,你可以说custom而不是Foo.custom:
class Foo(object):
custom = 1
def __init__(self, mycustom=custom):
self._custom = mycustom
但请注意,稍后更改 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
通过使用哨兵默认值,你可以得到你想要的:
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
【讨论】:
is 完成。
我们要做的是以下
class Foo( object ):
custom = 1
def __init__( self, arg=None )
self._custom = self.custom if arg is None else arg
这绕过了名称Foo 是否已定义的令人困惑的问题。
【讨论】:
类体在定义其自身的类之前执行,因此默认参数值不能引用该类。只需将 custom 设为默认值(无类限定)即可。
【讨论】:
我收到以下错误:
Traceback (most recent call last):
Line 1, in <module>
class Foo(object):
Line 3, in Foo
def __init__(self, custom=Foo.custom):
NameError: name 'Foo' is not defined
这是因为名称 Foo 正在被定义为 __init__ 函数被定义的过程中,并且当时不完全可用。
解决方案是避免在函数定义中使用名称Foo(我还将custom参数重命名为acustom以区别于Foo.custom):
class Foo(object):
custom = 1
def __init__(self, acustom=custom):
self._custom = acustom
x = Foo()
print x._custom
【讨论】: