Is there a better way of coding this?

Sean Ross frobozz_electric at hotmail.com
Sun Jun 1 12:47:39 EDT 2003


Here's a possible solution, although it does not address your problem
completely. For instance, it requires optf to be a method that takes no
arguments (other than 'self').

def readonly(attrname, default, optf=None):
    def get(obj):
        value = default
        try:
            value = getattr(obj, attrname)
        except AttributeError:
            setattr(obj, attrname, default)
        if optf is not None:
            value = optf(obj)
        return value
    return property(fget=get)

class C:
    def __init__(self, data):
        self.data = data
    def adjustfoo(self):
        return 2*self.data
    # this statement must be placed somewhere
    # after the definition of your optf functor
    foo = readonly('_foo', 1, optf=adjustfoo)

instance = C(2)
print instance.foo

# outputs 4






More information about the Python-list mailing list