Python has a "really hidden encapsulation"?

dmytro starosud d.starosud at gmail.com
Sat Oct 23 11:30:50 CEST 2010


:-0
very interesting!
I've tried to run something like this:

.....................................................................
class en_property(property):
    ptr_pget = None
    ptr_pset = None

    def pset(self, _class, value):
        if (self.ptr_pset is None or type(value) == tuple):
            self.ptr_pset = value[1]
            self.ptr_pget = value[0]
        else:
            self.ptr_pset(self, _class, value)

    def pget(self, _class):
        return self.ptr_pget(self, _class)

    def __init__(self, pget, pset):
        property.__init__(self, self.pget, self.pset)
        self.ptr_pget = pget
        self.ptr_pset = pset

class segment():
    def __new__(self):
        class _segment():
            def min_set(prop, self, p_min):
                if (self.v_max is not None) and (p_min > self.v_max):
                    raise AttributeError('It must be: "min < max"')
                else:
                    prop.v_min = p_min

            def min_get(prop, self):
                if 'v_min' in dir(prop):
                    return prop.v_min

            def max_set(prop, self, p_max):
                if (self.v_min is not None) and (p_max < self.v_min):
                    raise AttributeError('It must be: "min < max"')
                else:
                    prop.v_max = p_max

            def max_get(prop, self):
                if 'v_max' in dir(prop):
                    return prop.v_max

            def class_set(prop, self, value):
                raise AttributeError('Cannot change "__class__"')

            def class_get(prop, self):
                class segment():
                    v_min, v_max = None, None
                return segment

            v_min = en_property(min_get, min_set)
            v_max = en_property(max_get, max_set)
            __class__ = en_property(class_get, class_set)
            del min_get, min_set, max_get, max_set, class_get,
class_set
        obj = _segment()
        return obj
.....................................................................
>>> s = segment()
>>> t = segment()
>>> s.v_min, s.v_max = -1, 1
>>> t.v_min, t.v_max = 10, 20
.....................................................................

I've even override attribute __class__ (it is an property),
and code "s.__class__.v_min.v_min" raises an exception.
but we still can change the value of property using direct link:
>>> type(s).v_min.v_min = 10

I think I'm being realized that Python allows to do everything.
Maybe I will not try to find "really hidden encapsulation". :)

p.s. what do you think about the presence of two fields v_min (in
first message):
“s.__dict__['v_min']” and “s.v_min”?



More information about the Python-list mailing list