栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将对象转换为Python中的子类?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将对象转换为Python中的子类?

由于库函数返回A,因此如果不更改它就不能使其返回B。

您可以做的一件事是编写一个函数,以获取A实例的字段并将其复制到新的B实例中:

class A: # defined by the library    def __init__(self, field):        self.field = fieldclass B(A): # your fancy new class    def __init__(self, field, field2):        self.field = field        self.field2 = field2 # B has some fancy extra stuffdef b_from_a(a_instance, field2):    """Given an instance of A, return a new instance of B."""    return B(a_instance.field, field2)a = A("spam") # this could be your A instance from the libraryb = b_from_a(a, "ham") # make a new B which has the data from aprint b.field, b.field2 # prints "spam ham"

编辑:根据您的情况, 构图而不是继承 可能是一个不错的选择;那是您的B类可能只包含A的实例,而不是继承:

class B2: # doesn't have to inherit from A    def __init__(self, a, field2):        self._a = a # using composition instead        self.field2 = field2    @property    def field(self): # pass accesses to a        return self._a.field    # could provide setter, deleter, etca = A("spam")b = B2(a, "ham")print b.field, b.field2 # prints "spam ham"


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/647264.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号