首页 文章

Python中描述符的使用示例[关闭]

提问于
浏览
2

我希望这个问题不是太开放 . 阅读http://python-history.blogspot.com/2010/06/inside-story-on-new-style-classes.html之后,我终于在Python中使用了"get"描述符 . 但是我在他们身上看到的所有内容都描述了它们如何用于实现静态方法,类方法和属性 .

我很欣赏这些的重要性,但是Python中的描述符有哪些其他用途?我希望我的代码能做什么样的魔术才能使用描述符(或至少最好用描述符实现)来实现?

1 回答

  • 3

    延迟加载的属性:

    import weakref
    class lazyattribute(object):
        def __init__(self, f):
            self.data = weakref.WeakKeyDictionary()
            self.f = f
        def __get__(self, obj, cls):
            if obj not in self.data:
                self.data[obj] = self.f(obj)
            return self.data[obj]
    
    class Foo(object):
        @lazyattribute
        def bar(self):
            print "Doing a one-off expensive thing"
            return 42
    
    >>> f = Foo()
    >>> f.bar
    Doing a one-off expensive thing
    42
    >>> f.bar
    42
    

相关问题