【发布时间】: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