[Python] Python OO pattern, involving both 2D and 3D representations [closed]

Discussão em 'Python' iniciado por Stack, Março 8, 2025.

  1. Stack

    Stack Membro Participativo

    I working with Octahedral Faces both in 2D and 3D. There's a matrix which rotates one to the other, but both of them have methods and properties which are unique to either representation.

    I was thinking of using an ABC, and then Face2D/Face3D as subclasses - but I'm not sure that's the right approach.

    Instead of an ABC, how about a decorator class of some sort that implements as_2D/as_3D methods - which keeps either/both as they are required?

    Up until now I have been using a general Face class, but it's getting unwieldy. This is why I am thinking of subclassing.

    I'm suggesting something like the following

    class Face:
    def __init__(self, name, vertices):
    self.name = name
    self.vertices = vertices
    self._2d = None
    self._3d = None

    def to_3d(self):
    """ 3D instantiation """
    raise NotImplementedError

    def to_2d(self):
    """ 2D instantiation """
    raise NotImplementedError

    def as_3d(self):
    if self._3d is None:
    self._3d = self.to_2d()
    return self._3d

    def as_2d(self):
    if self._3d is None:
    self._3d = self.to_2d()
    return self._2d


    class Face3D(Face):
    def __init__(self, name, vertices):
    super().__init__(name, vertices)
    self._3d = self


    class Face2D(Face):
    def __init__(self, name, vertices):
    super().__init__(name, vertices)
    self._2d = self



    I am wary of this though - it sort of feels like I am doing some sort of weird inheritance hierarchy trick which could be better dealt with via composition instead of inheritance.

    I am not looking for an opinion. I am asking for a clear explanation of how to approach this sort of issue from an OO standpoint. The question is about how to identify suitable class relations.

    Continue reading...

Compartilhe esta Página