class level properties

Charles D Hixson charleshixsn at earthlink.net
Sun Apr 13 01:33:44 CEST 2008


Arnaud Delobelle wrote:
> On Apr 12, 8:36 pm, Charles D Hixson <charleshi... at earthlink.net>
> wrote:
>   
>> I'm trying to construct read-only variables at the class level.  I've
>> been unsuccessful.  Any suggestions?
>>
>> Mixing @classmethod and @property doesn't appear to produce workable
>> code.  Ditto for mixing @classmethod and __getattr__.  (The property
>> approach compiles, but execution says that you can't execute properties.)
>>
>> I've got a rather large number of variables, so I don't want to define
>> function accessors for each of them, and I *REALLY* don't want to have
>> to access them as functions rather than variables or properties.
>>     
>
> Metaclasses, of course!
>
>   
>>>> class MetaX(type):
>>>>         
> ...     @property
> ...     def spam(self): return 'eggs'
> ...
>   
>>>> class X(object):
>>>>         
> ...      __metaclass__ = MetaX
> ...
>   
>>>> X.spam
>>>>         
> 'eggs'
>   
>
> HTH
>
> --
> Arnau
Thanks.  I can make that work.  Is it possible to move the entire 
implementation of the interpretation of  _valueMap, below, into 
properties in some similar way?  I'm referring to the part managed by 
__getattr__ below.
I want a hundred or so read-only variables, and I'm not sure the best 
way to achieve it.

class    MetaROVars(type):
    @property
    def    simple(self):
        return    "simple example working"


class test(object):
    __metaclass__    =    MetaROVars
    _valueMap    =    {
            "t1"    : (3,    "Concept decay rate", "[1, 99]"),
            "t2"    :    (10,    "TaskLink decay rate", "[1, 99]"),
            }
   
    #@classmethod
    def    __getattr__(self, name):
        if    name not in test._valueMap:
            raise AttributeError, name
        return    test._valueMap[name][0]

    def    describe    (self, name):
        if    name not in test._valueMap:
            raise AttributeError, name
        return    test._valueMap[name][1] + ", lying in the range " + 
test._valueMap[name][2]


p    =    test()
print    p.t1
print    p.describe("t1")
print    p.t2
print    test.simple




More information about the Python-list mailing list