python 类初始化的注意事项

自己写了一个 Chessboard 类:
class Chessboard(VGroup):
    def __init__(
        self,
        shape: tuple = (8, 8),
        height: float = 1,
        width: float = 2,
#         depth 属性指的是厚度,不是指处于 z 轴的高度
        depth: float = 3,
        color: Color = BLUE,
        sheen: float = 0.2,
        **kwargs
    ):
        super().__init__(**kwargs)
        self.shape = shape
        self.height = height
        self.width = width
        self.depth = depth
        self.color = color
        self.sheen = sheen
        nr, nc = self.shape
        cube = Cube().set_sheen(self.sheen).set_color(self.color)
#         replace 方法指的是 mobject1 移动到 mobject2 的位置,且大小和 mobject2 一致
        self.add(*[cube.copy() for x in range(nc * nr)])
        self.arrange_in_grid(nr, nc, buff=1)
        self.stretch_to_fit_height(self.height)
        self.stretch_to_fit_width(self.width)
        self.stretch_to_fit_depth(self.depth)

但是 stretch_to_fit 函数没有生效,最后发现在 __init__ 函数中使用传入的属性时最好不要用 self.attribute 的形式,例如 self.height,而是之间使用 height

另外,代码部分最好写在 super().__init__() 函数后面,否则会报错

posted @ 2023-01-11 19:36  树叶本子  阅读(48)  评论(0)    收藏  举报