如何解决 AssertionError on checking type() by assert?

How to resolve AssertionError on checking type() by assert?

我正在尝试使用 assert 函数检查我在代码中输入的对象是否是形状点、线串或多边形几何体。 我的代码总是产生这个'AssertionError'我放在代码下面,我不明白为什么或解决它...

def get_centroid(geom):
    assert type(geom) == 'shapely.geometry.point.Point' or type(geom) == 'shapely.geometry.linestring.LineString' or type(geom) == 'shapely.geometry.polygon.Polygon', "Input should be a Shapely geometry!"
    return print(geom.centroid)

points1 = [Point(45.2,22.34),Point(100.22,-3.20)]
line1 = create_line_geom(points1)

get_centroid(line1)
AssertionError                            Traceback (most recent call last)
<ipython-input-33-6cb90e627647> in <module>
----> 1 get_centroid(line1)

<ipython-input-30-9f649b37e9c2> in get_centroid(geom)
      1 # YOUR CODE HERE
      2 def get_centroid(geom):
----> 3     assert type(geom) == 'shapely.geometry.linestring.LineString', "Input should be a Shapely geometry!"
      4     return print(geom.centroid)

AssertionError: Input should be a Shapely geometry!

type() returns the class itself, not the class's name. So you should use something more like type(geom) == Point. However, you can do multiple "or equals" more easily by using in to check set membership:

type(geom) in {Point, LineString, Polygon}

请注意,这不包括子类。要包含它们,请使用 isinstance():

any(isinstance(geom, t) for t in {Point, LineString, Polygon}))