【发布时间】: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