views:

620

answers:

1

I'm using boto to manage some EC2 instances. It provides an Instance class. I'd like to subclass it to meet my particular needs. Since boto provides a query interface to get your instances, I need something to convert between classes. This solution seems to work, but changing the class attribute seems dodgy. Is there a better way?

from boto.ec2.instance import Instance as _Instance

class Instance(_Instance):
    @classmethod
    def from_instance(cls, instance):
        instance.__class__ = cls
        # set other attributes that this subclass cares about
        return instance
+1  A: 

I wouldn't subclass and cast. I don't think casting is ever a good policy.

Instead, consider a Wrapper or Façade.

class MyThing( object ):
    def __init__( self, theInstance ):
        self.ec2_instance = theInstance

Now, you can subclass MyThing as much as you want and you shouldn't need to be casting your boto.ec2.instance.Instance at all. It remains as a more-or-less opaque element in your object.

S.Lott
+1 Composition over inheritance when possible.
Carl Meyer
The class I'd like to subclass is much more complex than the additions I'm making (really just a few attributes). To expose all the functionality in the wrapped class, I'd need a lot of wrapped functions/properties. I understand the composition v. inheritance issue, but going the composition route seems like more trouble than it's worth in this case.
iconoplast
@iconoplast: "I'd need a lot of wrapped functions/properties". Why? The instance is always named `myThing.ec2_instance`. Why can't you call the EC2 instance properties and methods directly? What else is going on?
S.Lott
I guess you're right. I was just trying to be clever about it.
iconoplast