慕码人2483693
以下代码假设您有理由使用self.facesdict 而不是front直接在实例上设置属性和/或想要为self.faces.否则,这个练习是毫无意义的,因为正如 Corentin Limier 指出的那样,您可以简单地设置self.front = Face(1),等等。您可以使用描述符、保存人脸名称的类变量和类装饰器。将描述符视为可重用的属性。在以下示例代码中,我仅出于演示目的num向Face和 face添加了一个实例变量'side'。class FaceDescriptor: def __get__(self, instance, owner): # your custom getter logic # dummy implementation if instance is not None: return instance.faces[self.face] def __set__(self, instance, value): # your custom setter logic # dummy implementation instance.faces[self.face] = valuedef set_faces(cls): for face in cls._faces: desc = FaceDescriptor() desc.face = face setattr(cls, face, desc) return clsclass Face(): def __init__(self, num): self.num = num @set_facesclass Cube(): _faces = ['front', 'side'] def __init__(self): self.faces = {face:Face(i) for i, face in enumerate(self._faces, 1)}在行动:>>> c = Cube() >>> c.front.num 1>>> c.side.num 2>>> c.front = 'stuff' >>> c.front 'stuff'>>> c.faces {'front': 'stuff', 'side': <__main__.Face at 0x7fd0978f37f0>}