假设我有一个“合成”类和一个“图层”类。假设没有合成类的实例就不能存在图层类的实例,并且合成类的实例可以有多个图层实例。图层类的方法需要能够访问组合类的成员。这不完全是继承,因为每个图层实例都应该“包含”在组合类的单个实例中。
例如,如果我的合成类有三个成员“comp_width”、“comp_height”和一个名为“layers”的列表,列表中的每个层都应该能够调用它们自己的方法,这些方法可以访问“comp_width”和“comp_height”变量。
有没有什么方法可以在 Python 中设置这种特殊的类结构?如果是这样,你能举个例子吗?我不确定这是否可以完成。
请您参考如下方法:
一种方法是使用已有的composition 创建layer。这将允许您在创建过程中将 composition 对象传递给每个 layer 对象。
class Layer:
def __init__(self, composition, name):
if not isinstance(composition, Composition):
raise TypeError(
'instance of the layer class cannot exist without an instance '
'of the composition class')
self.composition = composition
self.name = name
def __repr__(self):
return self.name
def get_composition_info(self):
return (
'composition [{}] with size [{} x {}] and layers {}'
.format(
self.composition.name,
self.composition.height,
self.composition.width,
self.composition.layers))
class Composition:
def __init__(self, name, height, width):
self.layers = list()
self.name = name
self.height = height
self.width = width
def __repr__(self):
return self.name
def create_layer(self, name):
layer = Layer(self, name)
self.layers.append(layer)
return layer
comp = Composition('my_composition_1', 10, 2)
l_1 = comp.create_layer('layer_1')
l_2 = comp.create_layer('layer_2')
print(comp)
print(comp.layers)
print(l_1)
print(l_1.get_composition_info())
print() 的输出:
my_composition_1
[layer_1, layer_2]
layer_1
composition [my_composition_1] with size [10 x 2] and layers [layer_1, layer_2]
