我正在编写一些代码,其中一个类定义了一些嵌套类(以使事物更整洁并按用途分组)。我希望嵌套类使用封闭类的属性(见下文)。该属性将提供一个设置在封闭类之上的默认值,而不是一个“魔数(Magic Number)”。
class Progress_indicator:
#use this attribute to provide a default value
number_of_dots=5
class Dots:
#the attribute above provides a default value here:
def __init__(self, number = Progress_indicator.number_of_dots):
self._current=0
self._number_of_dots=number
现在,当运行上面的代码时,我得到:
NameError: name 'Progress_indicator' is not defined
来自包含__init__
的行。
我知道这是由于 python 定义了一个命名空间,因为它看到了一个类声明,但实际上在处理完整的类声明之后将该命名空间分配给一个名称(在本例中为 Progress_indicator )(即留下了缩进的代码块)。重新定义 __init__
以使用 self.number_of_dots
而不是 Progress_indicator.number_of_dots
会生成相同的错误(因为这里没有继承)。我尝试过的所有引用文献(书籍和大量网络)都表明上述内容应该有效。但事实并非如此。是否有一种巧妙的方法来访问封闭类中定义的属性来为上述函数参数提供默认值?
我使用的是python3.2。
最佳答案
使用None
作为占位符值,如果未提供则替换默认值。
class Indicator:
number_of_dots = 5
class Dots:
def __init__(self, number = None):
if number is None:
number = Indicator.number_of_dots
self._current = 0
self._number_of_dots = number
这可能有点冗长,但您可以避免命名空间问题。或者您可以使用self._number_of_dots = number or Indicator.number_of_dots
如果0
不是可用作参数的有效值。
你也可以这样做def __init__(self, **kwargs)
然后kwargs.pop('number', Indicator.number_of_dots)
,但这可能不太清楚。
关于python - 从 python 中的其他属性定义中访问类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7300506/