Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclassing Polygon in Shapely

Tags:

python

shapely

I'm working with Shapely in Python and trying to subclass the Polygon class. However, I'm encountering an error when trying to add a custom attribute during object creation. Could you please provide guidance on how to subclass the Polygon class in Shapely and add custom attributes without running into this error?

This is what I tried so far:

from shapely.geometry import Polygon


class CustomPolygon(Polygon):

    def __init__(self, shell=None, holes=None, name=None):
        super().__init__(shell, holes)
        self._name = name

    @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")

And this is the error I get:

polygon1 = CustomPolygon([(0, 0), (0, 1), (1, 1), (1, 0)], name="Polygon1")
TypeError: __new__() got an unexpected keyword argument 'name'
like image 487
Gilfoyle Avatar asked Feb 05 '26 11:02

Gilfoyle


1 Answers

You need to downgrade shapely to version 1.7 unfortunately. They intentionally got rid of any subclassing capability in 1.8 and they explicitly say they aren't going to support it anymore. See the issue here:

https://github.com/shapely/shapely/issues/1698

like image 119
Tyler Habowski Avatar answered Feb 08 '26 00:02

Tyler Habowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!