【问题标题】:Python Open Closed Principle when your objects could be a list of instances?当您的对象可以是实例列表时,Python 开放封闭原则?
【发布时间】:2019-07-18 18:52:05
【问题描述】:

我有许多可以“jsonify”的不同对象,这些是自定义对象类型:

class Jsonable(ABC):
    @abstractmethod
    def extract_json():
        pass # return json of self

class Organization(Jsonable):
    # implements the abstract method, all good here
    def extract_json():
        return # some json of self, great!

class Feature(Jsonable):
    # implements the abstract method, all good here
    def extract_json():
        return # some json of self, great!

我有一个函数,我想传入许多不同类型的“Jsonable”并为它们获取 json,但有一个问题,“str”类是该函数的有效类型,也是一个 List [Jsonable] 也有效,如何有一个干净的函数返回数据?

def extract(data: Union[Jsonable, List[Jsonable], str):
    if isinstance(data, str): 
        # do something about string
        # not great but I can live with this, it will never change
    return data.extract_json() # ok for the standard types (Org above)
    # what about List[Jsonable]?
    # I have many types, Organization above is one example

如何使这个提取函数不违反 OCP 并获得一种从这些类型中抽象出数据的干净方法?我应该也可以从列出的类型中干净地获取 json 吗?

List 并不能真正扩展 Jsonable,那么我该如何干净利落地处理呢?

【问题讨论】:

    标签: python design-patterns open-closed-principle


    【解决方案1】:

    如果你的签名看起来像那样,你基本上是在告诉调用者他们必须传入这三种类型中的一种,而且你总是知道Jsonables 有.extract_json(),所以...

    def extract(data: Union[Jsonable, List[Jsonable], str]):
        if isinstance(data, str):
            return ...
    
        if isinstance(data, list):  # given the signature it's implicit everything is jsonable
            return [item.extract_json() for item in list]
    
        return item.extract_json()
    

    但是,如果你说的是真的 JSON,我建议查看 json.dump()default() 回调,当有一个不知道如何处理的对象时调用它:

    def handle_object(obj):
        if isinstance(obj, Jsonable):
            return obj.extract_json()  # should really return something that's json encodable now
        raise TypeError(f'Not sure how to JSONify {obj}')
    
    # ...
    json.dumps(anything, default=handle_object)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-17
      • 1970-01-01
      相关资源
      最近更新 更多