从python中的其他属性定义中访问类属性

时间:2011-09-04 16:14:17

标签: python python-3.x

我正在编写一些代码,其中一个类定义了一些嵌套类(以保持整洁和按目的分组)。我希望嵌套类使用封闭类的属性(见下文)。此属性将提供在封闭类之上设置的默认值,而不是“幻数”。

 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。

1 个答案:

答案 0 :(得分: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),但这可能不太清楚。