如何在Python中设置属性预先检查其值?

时间:2012-06-19 22:51:39

标签: python properties

我有一个变量,我需要从远程服务器获取其内容,所以我宁愿等到它的内容真的需要。我想如果使用一个属性,但似乎我做错了。根据例子。

def download():
    return 'content from remote server'

class Foo:
    def __init__(self):
        self.downloaded_bar = False
        self.bar = None

    @property
    def bar():
        if not self.downloaded:
            self.bar = download()
            self.downloaded = True
        return self.bar

f = Foo()
print f.bar #prints None, I expected 'content from remote server'

我做错了什么?

1 个答案:

答案 0 :(得分:5)

你需要让Foo成为一个新的样式类,让描述符起作用。 您也不能拥有与该属性同名的媒体资源,因此我将.bar更改为._bar 您还需要修复拼写错误(downloaded_bar)

def download():
    return 'content from remote server'

class Foo(object):                    # Inherit from object for new style class!
    def __init__(self):
        self.downloaded = False
        self._bar = None

    @property
    def bar(self):
        if not self.downloaded:
            self._bar = download()
            self.downloaded = True
        return self._bar

f = Foo()
print f.bar     def download():
    return 'content from remote server'

实际上,您可能根本不需要downloaded属性

class Foo(object):
    def __init__(self):
        self._bar = None

    @property
    def bar(self):
        if self._bar is None:
            self._bar = download()
        return self._bar

f = Foo()
print f.bar