在python中命名坐标

Ter*_*how 2 python

我正在尝试写出一个3d对象的坐标,但我不确定如何列出它.

到目前为止我有:

class threed:
    def __init__(self,length,width,height):
        self.h =height
        self.l = length
        self.w = width
        self.f=0
        self.lwh = (length,width,height)

for i in range(1,3):
      for j in range(1,3):
           for k in range(1,3):
                coordinates=threed(i,j,k)
Run Code Online (Sandbox Code Playgroud)

问题是我的函数每次都重写变量坐标,所以我不能访问坐标(1,1,1).

请注意,上面是2x2x2对象.

如何有效地编写它以便我可以根据需要引用任何坐标?

JBe*_*rdo 5

你可以做:

[threed(*x) for x in itertools.product(range(1, 3), range(1,3), range(1,3))]
Run Code Online (Sandbox Code Playgroud)

拥有每个对象.您也可以使用3个for循环:

[threed(x, y, z) for x in range(1, 3) for y in range(1,3) for z in range(1,3)]
Run Code Online (Sandbox Code Playgroud)

__repr__方法添加到您的课程中,您可以更轻松地查看结果.

def __repr__(self):
    return 'threed' + repr(self.lwh)
Run Code Online (Sandbox Code Playgroud)

所以第一个代码的输出将是:

[threed(1, 1, 1), threed(1, 1, 2), threed(1, 2, 1), threed(1, 2, 2), 
 threed(2, 1, 1), threed(2, 1, 2), threed(2, 2, 1), threed(2, 2, 2)]
Run Code Online (Sandbox Code Playgroud)

要允许threed比较对象,可以添加__eq__方法:

def __eq__(self, other):
    return self.lwh == other.lwh
Run Code Online (Sandbox Code Playgroud)