将类实例转换为子类

3 投票
1 回答
4498 浏览
提问于 2025-04-15 11:58

我正在使用 boto 来管理一些 EC2 实例。boto 提供了一个实例类。我想要创建一个这个类的子类,以满足我特定的需求。因为 boto 提供了一个查询接口来获取你的实例,所以我需要一些东西来在类之间进行转换。这个解决方案似乎可以用,但改变类属性看起来有点不太靠谱。有没有更好的方法呢?

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 个回答

7

我不建议使用子类和类型转换。我觉得类型转换通常不是个好主意。

相反,可以考虑使用包装器或者外观模式。

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

这样一来,你可以随意创建 MyThing 的子类,而根本不需要去转换你的 boto.ec2.instance.Instance。它在你的对象中仍然是一个比较不透明的元素。

撰写回答