加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 将类实例强制转换为子类

发布时间:2020-12-20 11:11:06 所属栏目:Python 来源:网络整理
导读:我正在使用 boto管理一些 EC2实例.它提供了一个Instance类.我想将其子类化以满足我的特殊需求.由于boto提供了一个查询接口来获取你的实例,我需要在类之间进行转换.这个解决方案似乎有效,但改变class属性似乎很狡猾.有没有更好的办法? from boto.ec2.instanc
我正在使用 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

解决方法

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读