2009-12-10 43 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