带有 setter 的自定义属性

发布于 2024-11-27 12:42:49 字数 375 浏览 2 评论 0原文

我正在寻找内置 property 的纯 Python 实现,以了解初始化的工作原理。我发现许多处理描述符接口(__get____set__),但没有一个描述setterdeleter方法。这是定义吗? org/moin/PythonDecoratorLibrary" rel="nofollow noreferrer">Python 装饰器库 (大致)它的实现方式是什么?

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 describing the setter or deleter methods. Is this definition in the Python Decorator Library (roughly) the way it is implemented?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

递刀给你 2024-12-04 12:42:49

属性是一个简单、直接的描述符。描述符协议由三个方法组成:__get____set____delete__。每个操作的属性只是调用用户提供的函数。

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

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
栖竹 2024-12-04 12:42:49

作为评论:有一种简单的方法可以向 Python 列表对象添加属性。在班级里扭曲。

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

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]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文