簡體   English   中英

Python的類變量和繼承

[英]Python's Class Variables and Inheritance

我這里有一些單位轉換程序的代碼; 由於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實例變量,但是在每個實例化上創建一個新集合似乎很浪費。 在這種特定情況下,具有共享行為似乎也是最佳的。

最好的做法是不將屬性定義為類的靜態屬性。 你所追求的是這樣的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM