延迟/调用类属性设置等于方法

时间:2012-10-07 02:45:36

标签: python django

问题

是否可以实例化一个对象,将该对象的属性设置为等于类方法,但在启用对该属性(obj.name)的访问时延迟调用该方法,而不必将其作为方法调用(obj.name()

背景

我有一个实例化对象的类。该实例化的一部分是将属性设置为等于数据库对象,这需要查找。在实例化许多对象(几百个)时,这种查找可能很慢。

我想以某种方式延迟查找,直到需要该信息。但是,我不想在对象上调用方法来进行查找,我只想访问属性(object.attribute

简单示例/我到目前为止所做的事

class Article(object):

    def __init__(self, id, author):
        self.id = id
        # Note the lack of () after lookup_author below
        self.author = self.lookup_author

        # Temporary holding place for author data
        self.__author = author

    def lookup_author(self):
        # A lookup that would be nice to delay / run as needed
        # Would be something like Author.objects.get(author=self.__author)
        # but set to something simple for this example
        return '<Author: John Doe>'

article1 = Article(1, 'John Doe')

# Returns the bound method
# E.g. <bound method Article.lookup_author of <__main__.Article object at 0x100498950>>
print article1.author

# Calls the method properly, however, you have to use the method calling
# notation of .state() versus .state which is more natural and expected
# for attributes
# Returns <Author: John Doe>
print article1.author()

1 个答案:

答案 0 :(得分:1)

使用属性,您可以让article1.author实际调用self.lookup_author并将其返回。

输出:

John Doe
<Author: John Doe>

bob
<Author: bob>

代码:

class Article(object):
    def __init__(self, id, author):
        self.id = id
        self.__author = None

    def lookup_author(self):
        return "John Doe"


    def __str__(self):
        return "<Author: {}>".format(self.author)

    @property
    def author(self):
        if self.__author is None:
            self.__author = self.lookup_author()
        return self.__author

    @author.setter
    def author(self,name):
        self.__author = name

article1 = Article(1, 'John Doe')
print "\n", article1.author
print article1

article1.author = 'bob'
print "\n", article1.author
print article1

出于某种原因,如果需要,在使用getter之前,__author甚至不必存在。你可以使用例外来做到这一点。