Reputation: 1270
Suppose I have a 'composition' class and a 'layer' class. Suppose that an instance of the layer class cannot exist without an instance of the composition class, and an instance of the composition class can have multiple layer instances. Methods of the layer class need to be able to access the members of the composition class. This isn't exactly inheritance, because each layer instance should be 'contained' within a single instance of the composition class.
For example, if my composition class has three members "comp_width," "comp_height", and a list called "layers", each layer in the list should be able to call their own methods which have access to the "comp_width" and "comp_height" variables.
Is there some way to set up this particular structure of classes in Python? If so, can you give an example? I'm not sure if this can be done.
Upvotes: 1
Views: 246
Reputation:
One approach is to create layer
s with already existing composition
. This will allow you to pass composition
object to every layer
object during the creation.
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())
Output of print()
s:
my_composition_1
[layer_1, layer_2]
layer_1
composition [my_composition_1] with size [10 x 2] and layers [layer_1, layer_2]
Upvotes: 1