2009-12-10 40 views
2

下面的python模塊意味着在python中「常量」處理的基礎。用例是:徵求意見:python類工廠的恆定值組

與它們的值一起屬於成字典
  • 與結合到類變量字典的類被創建並且instantinated遊程
    • 一個基團的一些常量(基本上是「名稱」)時間
    • 這個類的屬性是不變的名稱,它們的值是常量本身

    代碼:

    class ConstantError(Exception): 
        def __init__(self, msg): 
         self._msg = msg 
    
    class Constant(object): 
        def __init__(self, name): 
         self._name = name 
        def __get__(self, instance, owner): 
         return owner._content[self._name] 
        def __set__(self, instance, value): 
         raise ConstantError, 'Illegal use of constant' 
    
    def make_const(name, content): 
        class temp(object): 
         _content = content 
         def __init__(self): 
          for k in temp._content: 
           setattr(temp, k, Constant(k)) 
    
        temp.__name__ = name + 'Constant' 
        return temp() 
    
    num_const = make_const('numeric', { 
        'one': 1, 
        'two': 2 
    }) 
    
    str_const = make_const('string', { 
        'one': '1', 
        'two': '2' 
    }) 
    

    用途:

    >>> from const import * 
    >>> num_const 
    <const.numericConstant object at 0x7f03ca51d5d0> 
    >>> str_const 
    <const.stringConstant object at 0x7f03ca51d710> 
    >>> num_const.one 
    1 
    >>> str_const.two 
    '2' 
    >>> str_const.one = 'foo' 
    Traceback (most recent call last): 
        File "<stdin>", line 1, in <module> 
        File "const.py", line 16, in __set__ 
        raise ConstantError, 'Illegal use of constant' 
    const.ConstantError 
    >>> 
    

    請評論的設計,實施和對應到Python編碼準則。

  • 回答

    3

    以與Kugel相同的精神,但注意到collections.namedtuple非常相似..它是一個元組,因此是不可變的,並且它具有字段名稱。 Namedtuple是在Python 2.6中引入的。

    下面是如何使用namedtuple:

    import collections 
    
    def make_constants(variables): 
        n = collections.namedtuple('Constants', variables.keys()) 
        return n(**variables) 
    
    c = make_constants({"a": 2, "b": 76}) 
    print c 
    # the output is: 
    # Constants(a=2, b=76) 
    
    1

    最Python的方式是(我):

    my_fav_fruits = ('Apple', 'Orange', 'Strawberry', 'Chocolate Pudding') 
    lucky_numbers = (13, 7, 4, 99, 256) 
    

    你的設計似乎帶來了一些其他語言功能爲蟒蛇。你可以用類似的方式替代java接口。定義一個在任何方法調用中引發異常的類,並使子類從它派生並實現它們。我似乎發現,做這樣的事情沒有意義。我的'常量'和鴨式行爲一樣好,沒有接口(python文檔充滿了文件類對象)。

    +0

    +1你是正確的,在Python它常常可以歸結爲只是使用的類型的字典,元組和列表的正確組合,你就大功告成了。 – u0b34a0f6ae 2009-12-10 00:37:43

    +0

    「您的設計似乎將一些其他語言功能帶入python。」 這是故意的:-)基本上,我需要的東西足夠接近C宏。想象一下帶有「位域」參數的C函數,你想通過'ctypes'調用。那麼有一些符號代替數字來代替它們是很好的。 – 2009-12-10 00:38:48

    +0

    @ht:你必須意味着按位或Python中的'|'。注意sets和bitflags與'|'運算符的行爲相同 - 所以在Python中,如果你喜歡,你可以實現那些組合標誌作爲整數或集合。 – u0b34a0f6ae 2009-12-10 00:50:36

    2

    你的解決方案似乎相當過度設計。只需創建一個模塊並用大寫字母輸入常量。 我們都是成年人...

    #myconstants.py 
    
    ONE = 1 
    TWO = 2 
    THREE = 3