小编don*_*208的帖子

Python设计模式:嵌套抽象类

在下面的示例代码中,我希望每个car对象都由brake_system和组成,并engine_system作为属性存储在汽车上。

为了实现这一点,我定义了CarBreakSystem并将EngineSystem其定义为抽象类。每个子类Car需要定义其各自BreakSystemEngineSystem作为类属性的子类。

这种方法有潜在的问题吗?还是还有其他更适合处理嵌套抽象的设计模式?

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)

oop abstract-class design-patterns python-3.x

5
推荐指数
1
解决办法
532
查看次数

PyMongo:如何在不使用更新运算符的情况下 update_many ?

当修改不能直接使用更新运算符表达时,更新多个文档的最佳方法是什么?

这是我到目前为止所拥有的:

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)

有没有更好的办法?

python mongodb pymongo

2
推荐指数
1
解决办法
1549
查看次数