简体   繁体   English

用于API中对象启动的OO设计模式

[英]OO Design Pattern for object initiation in an API

When creating an API in python, I'm not sure what approach to take in creating an instance of a basic object with init. 在python中创建API时,我不确定使用init创建基本对象实例的方法。

When creating an instance of the object in the API, the user will most likely want the object to be one of two things: 在API中创建对象的实例时,用户很可能希望该对象成为以下两种情况之一:

  1. An instance of an object that already exists in what the API is being called against 调用API的对象实例
  2. Create a new object in what the API is being called against 在API被调用的内容中创建一个新对象

Is there an accepted design pattern for this? 是否有可接受的设计模式? Should init just create an empty object, and then the consumer must call a get or set method? init应该只创建一个空对象,然后消费者必须调用get或set方法吗? Or maybe init should take an argument as to if this is a get or set? 或者也许init应该讨论是否这是一个get或set? Or lastly, should get or set be inferred from the arguments to init? 或者最后,应该从init的参数中得到或设置?

I can't think of a design pattern to match exactly what you are describing, since: 我想不出一个与你所描述的完全匹配的设计模式,因为:

How about overloading the API to the following? 如何将API重载到以下?

When invoked with no arguments: 在没有参数的情况下调用时:

custom_API()

then just create a new basic object with some reasonable default values and let the consumer use get / set to configure it. 然后只需创建一个具有一些合理默认值的新基本对象,让消费者使用get / set来配置它。

When invoked with a lookup key of some sort: 使用某种查找键调用时:

custom_API("abc")

then return the corresponding object, or a list of objects of the lookup key is vague, or None if no matching object can be found. 然后返回相应的对象,或者查找键的对象列表是模糊的,如果找不到匹配的对象,则返回None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM