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