Python的类变量和Inheritan

2024-10-02 16:23:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我这里有一些单元转换程序的代码;由于Python的继承顺序,它抛出一个NameError。你知道吗

class _Units :
    _metric_unit_names   = {'metric'}
    _standard_unit_names = {'standard'}

class TemperatureUnits (_Units) :
    _metric_unit_names.update({'celsius', 'c'})
    _standard_unit_names.update({'fahrenheit', 'f'})

TemperatureUnits()

我想知道在这种情况下什么是“最好的”技术。我可以创建_metric_unit_names_standard_unit_names实例变量,但是在每个实例上创建一个新的集合似乎是浪费。在这种特殊情况下,拥有共同的行为似乎也是最佳的。你知道吗


Tags: 实例代码程序names顺序情况unitupdate
1条回答
网友
1楼 · 发布于 2024-10-02 16:23:07

最好的做法是不要将属性定义为类的静态属性。你想要的是这样的东西:

class _Units :
    def __init__(self):
        self._metric_unit_names   = {'metric'}
        self._standard_unit_names = {'standard'}

class TemperatureUnits (_Units) :
    def __init__(self):
        _Units.__init__(self)
        self._metric_unit_names.update({'celsius', 'c'})
        self._standard_unit_names.update({'fahrenheit', 'f'})

TemperatureUnits()

__init__之外定义属性会使它们成为类的静态成员(即_Units._metric_unit_names)。在init中定义它们会使它们成为类实例的属性(即my_units_instance._metric_unit_names)。你知道吗

相关问题 更多 >