Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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_Python 3.x - Fatal编程技术网

Python 使用工厂对象初始化基类

Python 使用工厂对象初始化基类,python,python-3.x,Python,Python 3.x,我有一个基类,我总是想用工厂对象创建它的对象 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

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

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
我想从工厂对象初始化派生类对象的基类。例如,我想通过调用ShapeMgr.new()创建圆的形状部分

我已尝试按如下方式定义形状构造函数:

SM = ShapeMgr()
class Circle:
  def __init__(self):
    global SM
    super() = SM.new()
但它告诉我,我不能为函数调用的结果赋值。如果我尝试:

    self = SM.new()
后来当我尝试访问圆形方法时,它说形状没有圆形方法


是否有任何方法可以使用工厂来创建派生类对象的基类部分?

如果希望
Circle
调用
Shape
进行初始化,只需执行以下操作:

class Circle(Shape):
    def __init__(self):  # important!
        super().__init__()
如果您的目标是让
圆圈
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中注册。shape的每个子项真的需要自己的管理器吗?每个
def
s都应该将
self
作为第一个参数。-Ignacio:是的,在我的实际应用程序中。但这与问题无关,所以我把它删除了-伊森:修好了。