将类实例强制转换为子类

ico*_*ast 3 python class subclass boto

我正在使用boto来管理一些EC2实例.它提供了一个Instance类.我想将其子类化以满足我的特殊需求.由于boto提供了一个查询接口来获取你的实例,我需要在类之间进行转换.这个解决方案似乎有效,但改变class属性似乎很狡猾.有没有更好的办法?

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
Run Code Online (Sandbox Code Playgroud)

S.L*_*ott 7

我不会继承和演员.我认为铸造不是一个好政策.

相反,请考虑Wrapper或Façade.

class MyThing( object ):
    def __init__( self, theInstance ):
        self.ec2_instance = theInstance 
Run Code Online (Sandbox Code Playgroud)

现在,您可以MyThing根据需要进行子类化,您根本不需要进行投射boto.ec2.instance.Instance.它仍然是对象中一个或多或少不透明的元素.