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 @   树叶本子  阅读(40)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示