【问题标题】:Object oriented programming: Point objects transferred into a list of tuples面向对象编程:点对象转移到元组列表中
【发布时间】:2021-02-20 21:58:27
【问题描述】:

我需要定义一个对象类,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)] 

【问题讨论】:

  • 你有一些语法问题。例如,类实例是用括号构造的,而不是方括号。如果您尝试传递点列表,则需要将该列表括在括号中。
  • 我在回答中添加了一些关于数据类的额外内容,以防您感兴趣。

标签: python-3.x oop


【解决方案1】:

你走在正确的轨道上,但你让事情变得对自己来说太难了。因为您已经创建了点列表,所以您应该存储它。

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

【讨论】:

    【解决方案2】:

    代码中的第一个问题是

    poly = Polyline[(2,4), (3,4) ,(4, 5)]
    

    不是创建类实例的有效方法,它应该看起来像

    poly = Polyline([(2,4), (3,4), (4,5)])
    

    其次,也许更重要的是,其中没有每个实例的变量。你需要类似的东西

    class Polyline
        def __init__(self, points):
            self.points = points
    

    完成此操作后,您应该有一个存储元组列表的类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 2011-07-09
      • 1970-01-01
      • 2015-02-12
      相关资源
      最近更新 更多