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

标签 python python-3.x

我正在编写一些代码,其中一个类定义了一些嵌套类(以使事物更整洁并按用途分组)。我希望嵌套类使用封闭类的属性(见下文)。该属性将提供一个设置在封闭类之上的默认值,而不是一个“魔数(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/

相关文章:

linux - 为什么 PyQt5 QFileDialog.getExistingDirectory 看不到 ~/.config/subdirectory?

python - Python 字符串 `\x` 中的前导 `\xaa` 是什么意思

python - 如何使用 openCV 保存帧的感兴趣区域?

python - cx_Freeze :Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings'

python - SQLALCHEMY 设置默认值 False 可空 True

python - 如何关闭 Python 正在使用的 mp3 文件?

生成长度为 n 的元组的 Pythonic 方法

python - Flask @route 错误

python - Pycharm:类型提示项目列表

python-3.x - 属性错误 : module 'concurrent' has no attribute 'futures' when I try parallel processing in python 3. 6