You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用基类Polygon的类方法正确初始化派生类Square?

解决Polygon子类Square初始化的类方法问题

问题核心

  • 调用super().from_number_of_vertices_and_edge_length时,父类类方法中的cls会指向Square而非Polygon,导致cls(vertices)尝试调用Square(vertices),但Square的__init__仅接受edge_length参数,引发参数不匹配错误。
  • 当前Square的__init__仅设置了edge_length属性,未将类方法生成的vertices绑定到自身实例。

解决方案

方案1:直接调用Polygon类方法获取顶点并赋值

修改Square的__init__,跳过继承链的类方法调用,直接用Polygon类调用类方法,确保生成Polygon实例后提取vertices赋值给Square:

class Square(Polygon):
    def __init__(self, edge_length):
        self.edge_length = edge_length
        # 直接调用Polygon类方法,此时cls指向Polygon,返回正确实例
        polygon_instance = Polygon.from_number_of_vertices_and_edge_length(4, edge_length)
        self.vertices = polygon_instance.vertices

方案2:调整Square初始化逻辑,复用父类构造

让Square先通过父类类方法生成顶点,再调用父类__init__完成vertices初始化,同时保留edge_length属性:

class Square(Polygon):
    def __init__(self, edge_length):
        # 获取父类类方法生成的顶点集合
        vertices = Polygon.from_number_of_vertices_and_edge_length(4, edge_length).vertices
        # 调用父类构造方法初始化vertices属性
        super().__init__(vertices)
        self.edge_length = edge_length

方案3:给Square添加专属类方法(推荐)

遵循面向对象设计规范,给Square添加专属类方法生成实例,避免继承带来的cls指向混淆:

class Square(Polygon):
    def __init__(self, vertices: list[Point], edge_length):
        super().__init__(vertices)
        self.edge_length = edge_length

    @classmethod
    def from_edge_length(cls, edge_length):
        # 调用Polygon类方法生成顶点,再创建Square实例
        vertices = Polygon.from_number_of_vertices_and_edge_length(4, edge_length).vertices
        return cls(vertices, edge_length)

# 使用方式
square = Square.from_edge_length(5)

内容的提问来源于stack exchange,提问作者CyrielN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 15:20:44