简体   繁体   English

Python的类变量和继承

[英]Python's Class Variables and Inheritance

I have here some code for a unit conversion program; 我这里有一些单位转换程序的代码; it throws a NameError , because of Python's inheritance order. 由于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()

I was wondering what the "best" technique for this situation would be. 我想知道这种情况的“最佳”技术是什么。 I could make _metric_unit_names and _standard_unit_names instance variables, but to make a new set on each instantiation seems wasteful. 我可以创建_metric_unit_names_standard_unit_names实例变量,但是在每个实例化上创建一个新集合似乎很浪费。 Also having a shared behavior seems optimal in this particular situation. 在这种特定情况下,具有共享行为似乎也是最佳的。

The best course of action is to not define the attributes as static attributes of the class. 最好的做法是不将属性定义为类的静态属性。 What you're after is something like this: 你所追求的是这样的:

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()

Defining attributes outside of __init__ cause them to be static members of the class (ie _Units._metric_unit_names ). 定义__init__之外的属性会导致它们成为类的静态成员(即_Units._metric_unit_names )。 Defining them within init cause them to be attributes of a class instance (ie my_units_instance._metric_unit_names ). init定义它们会使它们成为类实例的属性(即my_units_instance._metric_unit_names )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM