Skip to main content
 首页 » 编程设计

python之如何在 python 中设计类(oo 模式帮助)

2024年10月25日8bhlsheji

我正在实现一个“引擎”类(下面详细描述),但我不确定要使用哪种对象。我已经尝试阅读一些关于 OO 模式的资料,但我仍然不确定。我认为我的问题与语言无关,但首先我使用的是 Python。

我想创建一个类来进行一些初始化(例如数据库连接和一些其他配置),然后可以重复调用它来处理一些信息。对于信息位,我已将我的逻辑分解成一堆方法,但现在每个方法都有一个巨大的调用签名,因为我需要将各种东西传递到每个方法中。

调用代码看起来像这样:

db = get_a_db_connection() 
my_engine = Engine(db, config) 
while True: 
  my_info = get_info_from_somewhere() 
  my_engine.process_info(my_info) 

我拥有的实际 Engine 类看起来像这样:

class Engine(object): 
 
  def __init__(self, db, config): 
    self.db = db 
    # Also store the config - it's a little more complicated than 
    # this but I am abstracting away details that don't seem needed 
    self.config = config 
 
  def process_info(self, info): 
    foo = self.method1(info) 
    bar = self.method2(info, foo) 
    baz = self.method3(info, bar) 
    qux = self.method4(info, foo, bar, baz)  
    bla = self.method5(info, bar, baz, qux) 
 
  def method1(self, info): 
    # Do something and return intermediate info 
    return some_transformation_on_info 
 
  # Definitions for method2 - method5 (and more) follow 
 
  def method2(self, info, foo): 
    ... 
 
  <snip> 

似乎能够将这些中间事物存储为属性会很好,这样我就不需要每次都将它们作为参数传递。但是将它们存储为属性似乎并不合适,因为它们特定于一条信息而不是整个类。

这是我使用工厂模式创建一个实际处理信息的中间对象的情况吗?

请您参考如下方法:

这在很大程度上取决于参数的逻辑。但是您可以考虑定义一个具有两个属性的绑定(bind)对象:引擎和信息。然后将所有这些函数移动到绑定(bind)对象上。