0

问题

是否可以实例化一个对象,将该对象的属性设置为类方法,但延迟调用该方法,同时启用对该属性的访问(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()
4

1 回答 1

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

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

于 2012-10-07T03:04:45.037 回答