在实例化对象时,是否有可能传入一个对象应该派生自的类?
例如:
class Red(object):
def x(self):
print '#F00'
class Blue(object):
def x(self):
print '#00F'
class Circle(object):
def __init__(self, parent):
# here, we set Bar's parent to `parent`
self.x()
class Square(object):
def __init__(self, parent):
# here, we set Bar's parent to `parent`
self.x()
self.sides = 4
red_circle = Circle(parent=Red)
blue_circle = Circle(parent=Blue)
blue_square = Square(parent=Blue)
Run Code Online (Sandbox Code Playgroud)
哪个会产生类似的效果:
class Circle(Red):
def __init__(self):
self.x()
Run Code Online (Sandbox Code Playgroud)
但是,没有影响其他实例Circle.
也许您正在寻找的是一个班级工厂:
#!/usr/bin/env python
class Foo(object):
def x(self):
print('y')
def Bar(parent=Foo):
class Adoptee(parent):
def __init__(self):
self.x()
return Adoptee()
obj=Bar(parent=Foo)
Run Code Online (Sandbox Code Playgroud)
我同意@AntsAasma 的观点。您可能应该考虑使用依赖注入。至少在给出的示例中(我确信该示例已大大简化以说明您的问题),形状的颜色最好通过has-a 关系而不是is-a 关系来表示。
您可以通过将所需的颜色对象传递给构造函数、存储对其的引用并将函数调用委托给该对象来实现此目的。这极大地简化了实现,同时仍然保留了所需的行为。请参阅此处的示例:
class Red(object):
def x(self):
print '#F00'
class Blue(object):
def x(self):
print '#00F'
class Shape(object):
def __init__(self,color):
self._color=color
def x(self):
return self._color.x()
class Circle(Shape):
def __init__(self, color):
Shape.__init__(self,color)
self.x()
class Square(Shape):
def __init__(self, color):
Shape.__init__(self,color)
self.x()
self.sides = 4
red_circle = Circle(color=Red())
blue_circle = Circle(color=Blue())
blue_square = Square(color=Blue())
Run Code Online (Sandbox Code Playgroud)
编辑:修复了示例代码中构造函数参数的名称