我可以动态地将一个类的实例转换为另一个吗?

新手上路,请多包涵

我有一个描述棋子的课程。我为 Board 中的所有类型块制作了一个类,例如 Pawn、Queen、Keen 等……我在 Pawn 类中遇到了麻烦我想转换为 Queen 或其他具有类的对象(当 pawn 转到第 8 行时转换成另一种东西)我该怎么做?

 class Pawn:
    def __init__(self ,x ,y):
        self.x = x
        self.y = y
    def move(self ,unit=1):
        if self.y ==7 :
            self.y += 1
            what = raw_input("queen/rook/knight/bishop/(Q,R,K,B)?")
            # There is most be changed that may be convert to:
            # Queen ,knight ,bishop ,rook
        if self.y != 2 and unit == 2:
            print ("not accesible!!")
        elif self.y ==2 and unit == 2:
            self.y += 2
        elif unit == 1:
            self.y += 1
        else:
            print("can`t move over there")

原文由 Mojtaba Kamyabi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 304
1 个回答

实际上可以在 Python 中分配给 self.__class__ ,但你真的必须知道你在做什么。这两个类必须在某些方面兼容(都是用户定义的类,都是旧式或新式,我不确定 __slots__ 的使用)。此外,如果您执行 pawn.__class__ = Queen ,则 pawn 对象将不会由 Queen 构造函数构造,因此预期的实例属性可能不存在等。

另一种方法是像这样的复制构造函数:

 class ChessPiece(object):
  @classmethod
  def from_other_piece(cls, other_piece):
    return cls(other_piece.x, other_piece.y)

编辑:另见 Assigning to an instance’s class attribute in Python

原文由 wutz 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题