python-3.x - 面向对象编程:点对象转移到元组列表中
问题描述
我需要定义一个对象类 Polyline。参数应该是一个元组列表,表示顶点坐标的 x,y 值。
class Polyline:
def __init__(self, points):
point = (point[0], point[1])
for i in range(0,len(point)):
self.points.append(tuple(point[i]))
我知道代码没有意义,但我无法理解它。我希望 points 变量是由点对象组成的元组列表。
因此,这应该是有效的。
poly = Polyline[(2,4),(3,4),(4,5)]
解决方案
你在正确的轨道上,但你让事情对自己来说太难了。因为您已经创建了点列表,所以您应该存储它。
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__
方法。
方法如下:将其设为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