开发者

Custom property with setter

开发者 https://www.devze.com 2023-03-25 01:39 出处:网络
I am looking for a pure Python implementation of the property builtin to understand howinitialization works. I have found many that deal with the descriptor interface (__get__, __set__) but none descr

I am looking for a pure Python implementation of the property builtin to understand how initialization works. I have found many that deal with the descriptor interface (__get__, __set__) but none descri开发者_Python百科bing the setter or deleter methods. Is this definition in the Python Decorator Library (roughly) the way it is implemented?


Property is a simple, straightforward descriptor. Descriptor protocol consists of three methods: __get__, __set__ and __delete__. Property for each of those operations simply calls user-provided functions.

class my_property(object):
    def __init__(self, getter, setter, deleter):
        self.getter  = getter
        self.setter  = setter
        self.deleter = deleter

    def __get__(self, instance, owner):
        return self.getter(instance)

    def __set__(self, instance, value):
        self.setter(instance, value)

    def __delete__(self, instance):
        self.deleter(instance)

class Foo(object):
    def __init__(self):
        self._x = 42

    def get_x(self):
        print 'getter'
        return self._x

    def set_x(self, value):
        print 'setter'
        self._x = value

    def del_x(self):
        print 'deleter'
        del self._x

    x = my_property(get_x, set_x, del_x)

obj = Foo()
print obj.x
obj.x = 69
del obj.x
print obj.x


As a comment: there is a simple way to add property to a Python list object. Warp in a class.

>>> class Foo(list): pass
>>> l = Foo([1,2,3])
>>> l.foo = 'bar'
>>> l
[1, 2, 3]
0

精彩评论

暂无评论...
验证码 换一张
取 消