在下面的示例代码中,我希望每个car对象都由brake_system和组成,并engine_system作为属性存储在汽车上。
为了实现这一点,我定义了Car,BreakSystem并将EngineSystem其定义为抽象类。每个子类Car需要定义其各自BreakSystem和EngineSystem作为类属性的子类。
这种方法有潜在的问题吗?还是还有其他更适合处理嵌套抽象的设计模式?
from abc import ABC, abstractmethod
class Car(ABC):
"""
every car object should have an Engine object and a BrakeSystem object
"""
def __init__(self):
self.engine_system = self._engine_type()
self.brake_system = self._brake_type()
@property
@abstractmethod
def _engine_type(self):
raise NotImplementedError()
@property
@abstractmethod
def _brake_type(self):
raise NotImplementedError()
class EngineSystem(ABC):
pass
class BrakeSystem(ABC):
pass
class FooBrakeSystem(BrakeSystem):
pass
class FooEngineSystem(EngineSystem):
pass
class FooCar(Car):
_engine_type = FooEngineSystem
_brake_type …Run Code Online (Sandbox Code Playgroud) 当修改不能直接使用更新运算符表达时,更新多个文档的最佳方法是什么?
这是我到目前为止所拥有的:
def modify_doc(doc):
// modify doc in place
return modified_doc
for doc in db.collection.find({}):
mod_doc = modify_doc(doc)
collection.replace_one({'_id': mod_doc._id}, new_doc)
Run Code Online (Sandbox Code Playgroud)
我也在考虑:
def get_update_instructions(doc):
mod_doc = modify_doc(doc)
// take diff between doc and mod_doc and create update_instructions
return update_instructions
for doc in db.collection.find({}):
update_instructions = get_update_instructions(doc)
collection.update_one({'_id': mod_doc._id}, update_instructions)
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?