[python] attributes & descriptors
От: DemAS http://demas.me
Дата: 06.03.09 19:13
Оценка:
class UpperString(object):
    def __init__(self):
        self._value = ''
    def __get__(self, instance, klass):
        return self._value
    def __set__(self, instance, value):
        self._value = value.upper()

class MyClass(object):
    attribute1 = UpperString()
    def __init__(self):
        self.attribute2 = UpperString()

ex = MyClass()
print ex.attribute1
print ex.attribute2

ex.attribute1 = 'value'
print ex.attribute1

ex.attribute2 = 'value'
print ex.attribute2


Вывод:

''
<__main__.UpperString object at 0xb7d105cc>
VALUE
value


Вопрос — а чем собственно, attribute2 отличается от attribute1, что для
него не вызывается __get__() и __set__()? Просто раньше считал, что
attribute1 и attribute2 — это одна и та же конструкция языка — член-класса.
Posted via RSDN NNTP Server 2.1 beta
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.