我从数据库表中初始化的类很少。 我避免通过查询WeakValueDictionary中的id弱引用它来查询数据库(如果以前已经这样做过的话):
import weakref,gc
class anobject():
cache = weakref.WeakValueDictionary()
def __init__(self,id):
#query database for id
#Initiate instance with data from db
self.id = id
self.objectText = f'Object with id {self.id}'
anobject.cache[self.id] = self
def __new__(cls,id):
if id in cls.cache.keys():
return cls.cache[id]
else:
return object.__new__(cls)
def __str__(self):
return self.objectText
def main():
ob1 = anobject(0)
ob2 = anobject(1)
ob3 = anobject(0)
print(ob1,ob2,ob3)
print(anobject.cache[0])
del ob1
gc.collect()
print(anobject.cache[0])
if __name__ == "__main__":
main()
输出:
Object with id 0 Object with id 1 Object with id 0
Object with id 0
Object with id 0
我不担心对象过时,因为在对象生存期内数据库中的数据不会更改。
是否有更好,更Python化的方法来实现这一目标?由于将来我还需要通过除id以外的参数来初始化对象。