Python父子特定类结构

2024-04-26 13:09:58 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个“composition”类和一个“layer”类。假设layer类的实例不能没有composition类的实例,并且composition类的实例可以有多个layer实例。layer类的方法需要能够访问composition类的成员。这并不完全是继承,因为每个层实例都应该“包含”在复合类的单个实例中。你知道吗

例如,如果我的合成类有三个成员“comp\u width”、“comp\u height”和一个名为“layers”的列表,那么列表中的每个层都应该能够调用自己的方法,这些方法可以访问“comp\u width”和“comp\u height”变量。你知道吗

有什么方法可以在Python中设置这种特殊的类结构吗?如果是,你能举个例子吗?我不确定能不能做到。你知道吗


Tags: 实例方法layer列表layers成员width结构
1条回答
网友
1楼 · 发布于 2024-04-26 13:09:58

一种方法是用已有的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]

相关问题 更多 >