Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I dynamically convert an instance of one class to another?

Tags:

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") 
like image 250
Mojtaba Kamyabi Avatar asked Nov 09 '11 08:11

Mojtaba Kamyabi


People also ask

How do you convert from one class to another?

Class conversion can be done with the help of operator overloading. This allows data of one class type to be assigned to the object of another class type.

How do you convert one object to another in python?

Python is all about objects thus the objects can be directly converted into strings using methods like str() and repr(). Str() method is used for the conversion of all built-in objects into strings. Similarly, repr() method as part of object conversion method is also used to convert an object back to a string.

How do I convert from one object to another in C#?

Using the "as" operator, an object can be converted from one type to another. Unlike with explicit casting, if the conversion is not possible because the types are incompatible the operation does not throw an exception.


1 Answers

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

like image 174
wutz Avatar answered Sep 22 '22 11:09

wutz