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

Shapely中Polygon子类化及添加自定义属性的报错解决指引

解决Shapely Polygon子类化添加自定义属性的报错问题

错误原因

Shapely的Polygon属于不可变几何类型,实例的创建由__new__方法负责,而非__init__。你在__init__中添加了name参数,但创建实例时Python会先调用父类的__new__方法,而父类Polygon的__new__不识别name这个关键字参数,因此抛出TypeError。

解决方案

方案一:重写__new__方法接收自定义参数

直接在__new__中处理自定义参数,先创建父类实例再绑定属性:

from shapely.geometry import Polygon

class CustomPolygon(Polygon):
    def __new__(cls, shell=None, holes=None, name=None):
        # 调用父类__new__创建实例,仅传递它能识别的参数
        instance = super().__new__(cls, shell, holes)
        # 给实例添加自定义属性
        instance._name = name
        return instance

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

# 测试
polygon1 = CustomPolygon([(0, 0), (0, 1), (1, 1), (1, 0)], name="Polygon1")
print(polygon1.name)  # 输出: Polygon1

方案二:使用组合而非继承(更推荐)

由于Shapely几何类的设计特性,子类化可能带来隐藏问题(比如几何运算后返回原类型实例),用组合方式更稳妥:

from shapely.geometry import Polygon

class CustomPolygon:
    def __init__(self, shell=None, holes=None, name=None):
        self.polygon = Polygon(shell, holes)
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

    # 代理原Polygon的所有方法和属性,比如area、boundary等
    def __getattr__(self, attr):
        return getattr(self.polygon, attr)

# 测试
polygon1 = CustomPolygon([(0, 0), (0, 1), (1, 1), (1, 0)], name="Polygon1")
print(polygon1.name)  # 输出: Polygon1
print(polygon1.area)  # 输出: 1.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:26:19