1.2 定义多边形面类

如下代码定义了表示三维坐标中的一个多边形面的 Face 类。它主要由元素为坐标点的顶点列表构成。

技术要点:

# 表示多边形面。注意逆时针顶点方向是法向侧。
class Face(object):
    
    def __init__(self, *args):

        # [0 参数] 默认构造方法:点列表为空
        if (len(args) == 0):
            self.vertices = list()

        # [1 参数] 复制构造方法
        elif (len(args) == 1 and isinstance(args[0], Face)):
            other = args[0]
            # 做深拷贝, 每个点都做复制构造
            self.vertices = [Point(vertex) for vertex in other.vertices]

        # [1 参数] 构造方法
        elif (len(args) == 1 and isinstance(args[0], list)
                             and isinstance(args[0][0], Point)):
            vertices = args[0]
            # 做深拷贝, 每个点都做复制构造
            self.vertices = [Point(vertex) for vertex in vertices]

        else:
            raise ValueError("invalid args", args)
        
    # 重载 + 运算符:vertices 中每个 Point 都对给定点做加法
    def __add__(self, other:Point) -> object:
        for i in range(len(self.vertices)):
            self.vertices[i] = self.vertices[i] + other
    # 重载 - 运算符:vertices 中每个 Point 都对给定点做减法
    def __sub__(self, other:Point) -> object:
        for i in range(len(self.vertices)):
            self.vertices[i] = self.vertices[i] - other

    # 定义字符串化方法
    def __str__(self) -> str:
        # 这是字符串化序列最高效的方法
        return "F[" + ", ".join([vertex.__str__() for vertex in self.vertices]) + "]"

		# 定义绘制方法
    def render(self) -> None:
        glBegin(GL_LINE_LOOP)  # 绘制线环
        for vertex in self.vertices:
            glVertex3f(vertex.x, vertex.y, vertex.z)
        glEnd()

[1] Efficient String Concatenation in Python

https://waymoot.org/home/python_string/

https://www.cnblogs.com/legion/p/6225920.html