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?
In Python you don’t have a
castoperator – you can get around this by assigning the type to the instance’s__class__attribute:However, this is more error prone than
castin many other languages as the validity and safety of your “cast” is not verified by the compiler.For example, if
SubClasshad a method that accessed an attribute that was not available onSuperClassthen attempting to call that method onsuper_instancewould result in an error at run time, even though it appears to be a valid instance ofSubClass.