Python 当您的对象可以是实例列表时,开闭原则?

Python Open Closed Principle when your objects could be a list of instances?

我可以使用许多不同的对象 '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' class 是这个函数的有效类型,而且 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,那么我该如何干净利落地处理它?

如果您的签名看起来像那样,您基本上是在告诉呼叫者他们必须传递这三种类型中的一种,并且您总是知道 Jsonable.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)