2009-06-01 69 views
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 

回答

7

我不會繼承和投射。我不認爲鑄造是一個好策略。

相反,請考慮包裝或外觀。現在

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

,你也可以繼承MyThing只要你想盡可能多的,你不應該需要將您鑄造boto.ec2.instance.Instance可言。它仍然是對象中或多或少不透明的元素。

+0

+1在可能的情況下覆蓋繼承。 – 2009-06-02 05:05:03