Can I dynamically convert an instance of one class to another?
python
Solution
It is actually possible to assign to `self.__class__` in Python, but you really have to know what you're doing. The two classes have to be compatible in some ways (both are user-defined classes, both are either old-style or new-style, and I'm not sure about the use of `__slots__`). Also, if you do `pawn.__class__ = Queen`, the pawn object will not have been constructed by the Queen constructor, so expected instance attributes might not be there etc.
An alternative would be a sort of copy constructor like this:
class ChessPiece(object):
@classmethod
def from_other_piece(cls, other_piece):
return cls(other_piece.x, other_piece.y)
Edit: See also Assigning to an instance's __class__ attribute in Python
Problem
I have a class that describe chess pieces. I make for all type piece in the Board a class for example Pawn, Queen, keen, etc... I have a trouble in Pawn class I want to convert to Queen or other object that has a class (when pawn goto 8th row then convert to something another) how can I do this ? ``` 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") ```