不要直接调用export_json
from query
,而是将结果保存在实例属性中并返回self
以启用链接。然后export_json
在实例上查找已保存的查询,而不是将其作为参数。
@dataclass
class Data_Query:
hierarchic: str
sku: bool
pred_lenght: int
def query(self, db):
if (self.hierarchic == 'store' and self.sku == True):
self.x = db.aggregate([{...}]);
# self.export_json(x)
return self
def export_json(self, file):
try:
x = self.x
except AttributeError:
return
with open(f'/home/Documents/dataset/{file}', 'w') as fp:
for i in x:
json.dump(i, fp)
fp.write('\n')
del self.x
现在您可以编写data.query(db).export_json('abc.json')
,并且只有在实际上发生查询时才会编写 JSON 文件。
然而,这并不是最伟大的设计。没有什么export_json
是特定于您的班级的;它应该是一个接受结果和文件名的常规函数,如果查询返回任何结果,则在您进行查询后调用该函数。更像的东西
@dataclass
class Data_Query:
hierarchic: str
sku: bool
pred_lenght: int
def query(self, db):
if (self.hierarchic == 'store' and self.sku == True):
return db.aggregate([{...}])
def export_json(self, x, file):
with open(f'/home/Documents/dataset/{file}', 'w') as fp:
for i in x:
json.dump(i, fp)
fp.write('\n')
result = data.query(db)
if result is not None:
export_json(result, 'abc.json')
您可能会争辩说“当然export_json
与我的类有关;它假定这x
是对象的可迭代对象,这是由query
方法定义的东西。” 在这种情况下,您可能会考虑定义一个QueryResult
类,并为该类创建一个export_json
方法。然后返回一个 的实例,并且链接感觉不那么随意:您正在导出结果,而不是查询。DataQuery.query
QueryResult
# By the way, I am assuming there is more to this class than a query
# method; otherwise, there should probably just be a regular function
# that takes the db, hierarchic, and sku as arguments.
@dataclass
class DataQuery:
hierarchic: str
sku: bool
pred_length: int
def query(self, db):
result = None
if self.hierarchic == 'store' and self.sku:
result = db.aggregate(...)
return QueryResult(result)
class QueryResult:
def __init__(self, result):
self.result = result
def export_json(self, file):
if self.result is None:
return
with open(f'/home/Documents/dataset/{file}', 'w') as fp:
for i in x:
json.dump(i, fp)
fp.write('\n')
data.query(db).export_json('abc.json')