为了账号安全,请及时绑定邮箱和手机立即绑定

Python 类的相互依赖关系

Python 类的相互依赖关系

一只斗牛犬 2021-09-11 15:07:32
我有一个 python 类,用作进一步子类的基类。它包含一个方法,应该对所有子类采取相同的操作,例如我想把它放在基类中。问题是,这个方法应该返回子类的一个新实例。但是我因为基类位于子类的定义之前,所以我不能创建子类的新实例,因为它在基类的范围内是未知的:class Base:  def __init__(self, value):    self.value = value  def convert_child_classes(self, newclass):    newvalue = MakeUsableInNewclass(self.value)    newattr = MakeUsableInNewclass(self.subclassattr)    return newclass(newattr, newvalue)class Child1(Base):  def __init__(self, subclassattr, value)    super(Child, self).__init__(value)    self.subclassattr = subclassattr  def MethodForSubClassAttr(self):    ...do sth with self.subclassattr...class Child2(Base):  def __init__(self, subclassattr, value)    super(Child, self).__init__(value)    self.subclassattr = subclassattr  def SomeOtherSubClassAttrMethod(self):    ...do sth that is related to this class attr...如果我有一个 Child1 的实例,我希望能够用它的数据做一些事情,然后在调用 convert_child_classes(Child2) 时返回一个带有新值的 Child2 的实例:A = Child1('someattr', 5)B = A.convert_child_classes(Child2)现在 B 应该是 Child2 的一个实例,其值是从 Child1 计算出来的。但是由于 Base 类现在知道 Child1 或 Child2 是什么,它无法启动新类。
查看完整描述

2 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

这样的事情应该工作(未经测试):


class Measurement:


    @classmethod

    def from_other(cls, other):

        base = other.convert_to_base_unit()

        converted = cls.base_to_unit(base)

        return cls(converted)


    @classmethod

    def base_to_unit(cls, value):

        # Let the subclass implement this

        raise NotImplementedError


    def convert_to_base_unit(self):

        # Let the subclass implement this

        raise NotImplementedError

以这种方式实现,基类不需要了解子类的任何信息。基类提供模板方法 ( from_other),子类提供实现。


查看完整回答
反对 回复 2021-09-11
  • 2 回答
  • 0 关注
  • 169 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信