我希望这个问题不是太开放。阅读http://python-history.blogspot.com/2010/06/inside-story-on-new-style-classes.html之后,我终于在Python中“获取”了描述符。但是我在他们身上看到的所有内容都描述了它们如何用于实现静态方法,类方法和属性。
我很欣赏这些的重要性,但是Python中的描述符有哪些其他用途?我希望我的代码能做什么样的魔术只能使用描述符来实现(或至少使用描述符最好实现)?
答案 0 :(得分: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