【问题标题】:Use factory object to initialize base class使用工厂对象初始化基类
【发布时间】:2015-03-05 23:10:16
【问题描述】:

我有一个基类,我总是想用工厂对象创建它的对象。

class Shape:
  def __init__(self):
    pass

class ShapeMgr:
  def __init__(self):
    self.allShapes = []

  def new(self):
    newShape = Shape()
    self.allShapes.append( newShape )
    return newShape

我也有从那个基类派生的类。

class Circle(Shape):
  def __init__(self):
    pass

我想从工厂对象初始化派生类对象的基类。 IE,我想通过调用 ShapeMgr.new() 来创建圆的 Shape 部分。

我尝试如下定义 Shape 构造函数:

SM = ShapeMgr()
class Circle:
  def __init__(self):
    global SM
    super() = SM.new()

但它告诉我我不能分配给函数调用的结果。如果我改为尝试:

    self = SM.new()

然后当我尝试访问 Circle 方法时,它说 Shapes 没有 Circle 方法。

有没有办法使用工厂来创建派生类对象的基类部分?

【问题讨论】:

  • 每个有形的孩子真的需要自己的经理吗?
  • 你的每个defs 都应该有self 作为第一个参数。
  • -Ignacio:是的,在我的实际应用中。但这与问题无关,因此我已将其删除。 -Ethan:固定。

标签: python python-3.x


【解决方案1】:

如果您希望Circle 调用Shape 进行初始化,只需这样做:

class Circle(Shape):
    def __init__(self):  # important!
        super().__init__()

如果您的目标是让Circles 以ShapeMgr 结尾,那么您根本不需要担心基类(Shape),因为Shape 中的任何内容都不会导致注册发生。

更改ShapeMgr.new()以接受可选对象进行注册,如果没有给出对象则创建一个新的Shape

def new(self, obj=None):
    if obj is None:
        obj = Shape()
    self.allShapes.append(obj)

请注意,self 必须在 Python 中声明——没有它,您的方法将无法正常工作。

【讨论】:

  • 也许强调得不够——我不想调用 Shape 的构造函数。我想调用 SM.new() 以便在 ShapeMgr 中注册。
猜你喜欢
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多