3

botoを使用して、いくつかのEC2インスタンスを管理しています。インスタンスクラスを提供します。特定のニーズを満たすためにサブクラス化したいと思います。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
4

1 に答える 1

7

私はサブクラス化してキャストしません。キャスティングは決して良い政策ではないと思います。

代わりに、Wrapper または Façade を検討してください。

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

これで、好きなだけサブクラス化でき、MyThingキャストする必要がまったくなくなりましたboto.ec2.instance.Instance。オブジェクト内の多かれ少なかれ不透明な要素として残ります。

于 2009-06-01T20:03:39.997 に答える