你走在正确的轨道上,但你让事情变得对自己来说太难了。因为您已经创建了点列表,所以您应该存储它。
class Polyline:
def __init__(self, points):
self.points = points
您现在可以创建Polyline:
poly = Polyline([(2,4),(3,4),(4,5)])
或者如果你想提供一个存储列表:
my_points = [(2,4),(3,4),(4,5)]
poly = Polyline(my_points)
请注意,无论哪种方式,您都需要括号——正如我在上面的评论中所指出的那样。
现在,让我们验证它是否有效。我们将打印内容:
for point in poly.points:
print(point)
# (2, 4)
# (3, 4)
# (4, 5)
数据类:一个谩骂
哦,不是你问的那样——但是 Python 提供了一种免费的方式让你的 Polyline 类立即变得更加有用。可以自动获取:
- 更好的相等比较(与仅基于指针的默认值相比)
- 打印效果更好
- 一种自动的
__init__ 方法。
方法如下:make it a dataclass。
from dataclasses import dataclass # Requires Python ≥ 3.7
from typing import List
@dataclass
class Polyline:
points: List # For simplicity. Should really be List[Tuple[int, int]]
# That's it!
# Now let's make one and show you the magic.
# Automatically, you get an initializer.
my_points = [(2,4),(3,4),(4,5)]
poly = Polyline(my_points)
# Automatically, you get better string representation for printing.
print(poly)
# Polyline(points=[(2, 4), (3, 4), (4, 5)])
# Automatically, you get a correct equality comparison.
poly2 = Polyline([(2,4),(3,4),(4,5)])
print(poly == poly2)
# True