SuperDisk
SuperDisk

Reputation: 109

Type casting with non standard types in python

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".

Upvotes: 1

Views: 570

Answers (2)

Tadeck
Tadeck

Reputation: 137320

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?

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599550

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.

Upvotes: 3

Related Questions