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

sho*_*ner 19 python

我有一个描述棋子的课程.我为Board中的所有类型片段制作了一个类,例如Pawn,Queen,keen等...我在Pawn类中遇到麻烦我想转换为Queen或其他有类的对象(当pawn goto第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")
Run Code Online (Sandbox Code Playgroud)

wut*_*utz 23

它实际上可以self.__class__在Python中分配,但你真的必须知道你在做什么.这两个类必须在某些方面兼容(两者都是用户定义的类,都是旧式或新式,我不确定使用__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)
Run Code Online (Sandbox Code Playgroud)

编辑:另请参阅在Python中分配实例的__class__属性