[英]How to create lazy class variables?
I have a class with class variables that should be lazily created.我有一个 class 和 class 变量,应该延迟创建。 I have a working version for instance variables.我有一个实例变量的工作版本。 How do you implement one for class variables?你如何为 class 变量实现一个? The following is an example usage.下面是一个示例用法。
print(MyDatabase.users) # first call should load the users variable and return value
print(MyDatabase.users) # second call should return the stored value
The first error I got when I tried is AttributeError: type object 'MyDatabase' has no attribute 'users'
.我尝试时遇到的第一个错误是AttributeError: type object 'MyDatabase' has no attribute 'users'
。 Is there a way to catch the error in the class?有没有办法捕捉 class 中的错误?
Use@property
like so:像这样使用@property
:
class MyDatabase:
def __init__(self):
self._users = None
@property
def users(self):
if self._users is None:
# load users
print('users loaded')
self._users = ['u']
return self._users
db = MyDatabase()
print(db.users) # first call should load the users variable and return value
print(db.users) # second call should return the stored value
The loading happens only the first time:加载仅在第一次发生:
users loaded
['u']
['u']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.