1

I'm trying to wrap my brain around something here... Let's say that I have a simple setup of class inheritance:

class SuperClass(object):
    def __init__(self):
        self.var = 1

class SubClass(SuperClass):
    def getVar(self):
        return self.var

If I have an existing instance of SuperClass, is there a way that I can 'cast' it as SubClass, without creating a new instance?

dgel
  • 16,352
  • 8
  • 58
  • 75
  • 2
    Looks like [this](http://stackoverflow.com/a/3464154) may be what I'm looking for... – dgel Sep 20 '12 at 22:50
  • 2
    I think this is one of those ... just because you can doesnt mean you should... I would look at the Factory Design Pattern and instantiate it later, once you know what you want .. – Joran Beasley Sep 20 '12 at 22:51
  • Why do you want to? What are you hoping to accomplish? Why isn't `getVar` a `SuperClass` method? – Karl Knechtel Sep 20 '12 at 23:25
  • @KarlKnechtel: That was just a very simple example, that's not actually my code. – dgel Sep 21 '12 at 01:48
  • Well, yes; the point is that a proper solution to your problem depends on the details of your actual situation - because this isn't the sort of thing you want to solve with a general-purpose brute-force approach that tackles the issue the way you propose to. Wanting to do this sort of thing very frequently points to a design flaw. – Karl Knechtel Sep 21 '12 at 10:35

1 Answers1

2

In Python you don't have a cast operator - you can get around this by assigning the type to the instance's __class__ attribute:

>>> super_instance = SuperClass()
>>> super_instance.__class__ = SubClass
>>> print super_instance.getVar()
1

However, this is more error prone than cast in many other languages as the validity and safety of your "cast" is not verified by the compiler.

For example, if SubClass had a method that accessed an attribute that was not available on SuperClass then attempting to call that method on super_instance would result in an error at run time, even though it appears to be a valid instance of SubClass.

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • 2
    I'm not even sure I know what I'm really trying to do anymore- I'm trying to create a state machine to mimic some hardware. Need to give this some more thought... Your answer is correct, it works fine. But I agree that I should rethink what the heck I'm doing. – dgel Sep 20 '12 at 22:57
  • 1
    Don't use subtype to indicate the state in a state machine; use the internal state of the object (i.e., attributes). Even if you need different behaviour, you may find life much easier using the State/Strategy pattern. – Karl Knechtel Sep 21 '12 at 10:36