Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当对象可以是实例列表时,Python的开闭原则是什么?_Python_Design Patterns_Open Closed Principle - Fatal编程技术网

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

当对象可以是实例列表时,Python的开闭原则是什么?,python,design-patterns,open-closed-principle,Python,Design Patterns,Open Closed Principle,我有许多不同的对象可以“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(): re

我有许多不同的对象可以“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'类是这个函数的有效类型,还有一个列表[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,干净吗


列表不能真正扩展Jsonable,那么我该如何干净地处理它呢?

如果你的签名是这样的,你基本上是告诉呼叫者他们必须传入这三种类型中的一种,而且你总是知道
Jsonable
.extract_json()
,所以

def extract(数据:Union[Jsonable,List[Jsonable],str]):
如果存在(数据,str):
回来
如果isinstance(数据、列表):#给定签名,它是隐式的,所有内容都是可接受的
return[item.extract_json()用于列表中的项]
return item.extract_json()
但是,如果您所说的是真正的JSON,我建议您研究一下
JSON.dump()
default()
回调,当存在一个它不知道如何处理的对象时会调用它:

def handle_对象(obj):
如果存在(obj、JSA):
return obj.extract_json()#现在应该真正返回json可编码的内容
raise TypeError(f'不确定如何JSONify{obj}')
# ...
dumps(任意,默认值=handle\u对象)