dmytro starosud <d.staro...@gmail.com> writes: > Hello, > I'm Python beginner (from Ukraine). > I may have found the way to really hide attributes in Python class. > The whole control on this attribute is implemented inside of the > class. > *(code is below, Python 3) > You see that we can't get the reference to instance of class > "en_property" outside the class "segment", but in the inside we can. > > *It seems like there is no way to get the reference to field > “en_property.v_min” or “en_property.v_max”. > And object “s” has “two” attributes “v_min”: “s.__dict__['v_min']” and > “s.v_min”. > > Help me find the answer, Can I change this hidden attribute outside > the class? > Or is it just an interesting feature? > ...and Python has a "really hidden encapsulation"? > > code: > class en_property(property): > ptr_pget = None > ptr_pset = None > > def pset(self, _class, value): > 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 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 > > v_min = en_property(min_get, min_set) > del min_set, min_get > v_max = en_property(max_get, max_set) > del max_set, max_get > > ............................................................................ >>>> s = segment() >>>> s.v_min = -1 >>>> s.v_max = 1 >>>> s.v_min = 2 > Traceback (most recent call last): > File "<interactive input>", line 1, in <module> > File "D:\_dimka\I_Master\Programs_PyPg\enca.py", line 6, in pset > self.ptr_pset(self, _class, value) > File "D:\_dimka\I_Master\Programs_PyPg\enca.py", line 19, in min_set > raise AttributeError('It must be: "min < max"') > AttributeError: It must be: "min < max" >>>> s.__dict__['v_min'] = 2 >>>> s.__dict__['v_min'] > 2 >>>> s.v_min > -1 >>>>
One big problem is that the value of v_min and v_max is shared by all instances of segment: >>> s = segment() >>> s.v_min = 3 >>> t = segment() >>> t.v_min 3 >>> t.v_min = 5 >>> s.v_min 5 So it's not very useful (I suppose it's some kind of "class property"). Moreover I can still make v_min > v_max: >>> s = segment() >>> s.v_min = 5 >>> segment.v_max.v_max = 1 >>> s.v_min <= s.v_max False -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list