1

How for example would I convert a type from some external class to another one? I've searched around, and gotten stuff like "int to string" and stuff, but I'm talking about something like class "tile" converting to something else, such as "tile2".

1
  • 2
    Could you give an example of what you are trying to do? Commented Nov 27, 2011 at 22:15

2 Answers 2

3

There's no such thing as casting in Python. That's because there's no need for it: generally, any function that accepts a 'tile' object shouldn't care that it actually is a tile rather than a tile2, as long as it has the data and/or methods that it is expecting. This is called duck typing, and is a fundamental part of programming in a dynamically-typed language like Python.

Of course, it is possible to convert from one class to another, but there's no generic way of doing this. Your tile/tile2 classes would have to implement this themselves, probably by copying over the data elements.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 -- casting doesn't really make sense in the context of duck typing.
1

As Daniel mentioned in his answer, casting is not necessary in Python because of the way code for Python is (should be) usually written. The thing you may need however, is converting between non-standard types.

Converting should be probably supported within __init__ method within the class you want it to cast to, if you want to do it the way converting works for eg. int, str, list etc.:

class Tile: def __init__(self, val): # here paste the code making Tile object out of other objects, # possibly checking their types in the process pass 

and then (after adjusting __init__ to your needs) you should be able to cast it like that:

spam = Tile(ham) 

More comprehensive example for converting between types:

>>> class AmericanTile: def __init__(self, val=None): if isinstance(val, str): self.color = val elif isinstance(val, BritishTile): self.color = val.colour >>> class BritishTile: def __init__(self, val=None): if isinstance(val, str): self.colour = val elif isinstance(val, AmericanTile): self.colour = val.color >>> a = AmericanTile('yellow') >>> a.color 'yellow' >>> b = BritishTile(a) >>> b.colour 'yellow' 

Does it answer your question?

1 Comment

Yes, that makes enough sense! Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.