以下是我如何向从库中导入的类添加方法。如果我修改了库,我将在下一次库升级时丢失更改。我无法创建新的派生类,因为我无法告诉库使用我修改后的实例。所以我通过添加缺少的方法来修补现有的类:
# Import the standard classes of the shapely library
import shapely.geometry
# Define a function that returns the points of the outer
# and the inner polygons of a Polygon
def _coords_ext_int_polygon(self):
exterior_coords = [self.exterior.coords[:]]
interior_coords = [interior.coords[:] for interior in self.interiors]
return exterior_coords, interior_coords
# Define a function that returns the points of the outer
# and the inner polygons of a MultiPolygon
def _coords_ext_int_multi_polygon(self):
if self.is_empty:
return [], []
exterior_coords = []
interior_coords = []
for part in self:
i, e = part.coords_ext_int()
exterior_coords += i
interior_coords += e
return exterior_coords, interior_coords
# Define a function that saves outer and inner points to a .pt file
def _export_to_pt_file(self, file_name=r'C:\WizardTemp\test.pt'):
'''create a .pt file in the format that pleases thinkdesign'''
e, i = self.coords_ext_int()
with open(file_name, 'w') as f:
for rings in (e, i):
for ring in rings:
for x, y in ring:
f.write('{} {} 0\n'.format(x, y))
# Add the functions to the definition of the classes
# by assigning the functions to new class members
shapely.geometry.Polygon.coords_ext_int = _coords_ext_int_polygon
shapely.geometry.Polygon.export_to_pt_file = _export_to_pt_file
shapely.geometry.MultiPolygon.coords_ext_int = _coords_ext_int_multi_polygon
shapely.geometry.MultiPolygon.export_to_pt_file = _export_to_pt_file
请注意,相同的函数定义可以分配给两个不同的类。
编辑
在我的示例中,我没有向我的类添加方法,而是向我安装的开源库 shapely 添加方法。
在您的帖子中,您使用p.get_name = ... 将成员添加到对象实例p。我先定义一个函数_xxx(),然后用class.xxx = _xxx将它添加到类定义中。
我不知道你的用例,但通常你将变量添加到实例中,然后将方法添加到类定义中,这就是我向你展示如何将方法添加到类定义而不是实例的原因。
Shapely 管理几何对象并提供计算多边形面积、相互添加或减去多边形以及许多其他非常酷的东西的方法。
我的问题是我需要一些开箱即用的方法。
在我的示例中,我创建了自己的方法,该方法返回外部轮廓的点列表和内部轮廓的点列表。我做了两种方法,一种用于Polygon 类,另一种用于MultiPolygon 类。
我还需要一种将所有点导出为.pt 文件格式的方法。在这种情况下,我只制作了一种适用于 Polygon 和 MultiPolygon 类的方法。
此代码位于名为shapely_monkeypatch.py 的模块中(请参阅monkey patch)。导入模块时,定义了名称以_ 开头的函数,然后将它们分配给名称不带_ 的现有类。 (Python 中的约定是使用_ 来命名仅供内部使用的变量或函数。)