我这里有一些单元转换程序的代码;由于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
实例变量,但是在每个实例上创建一个新的集合似乎是浪费。在这种特殊情况下,拥有共同的行为似乎也是最佳的。你知道吗
最好的做法是不要将属性定义为类的静态属性。你想要的是这样的东西:
在
__init__
之外定义属性会使它们成为类的静态成员(即_Units._metric_unit_names
)。在init
中定义它们会使它们成为类实例的属性(即my_units_instance._metric_unit_names
)。你知道吗相关问题 更多 >
编程相关推荐