You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让父类高开销方法仅执行一次并供所有子类使用?

问题描述

我有两个继承自同一父类A的子类B和C。父类A中存在一个开销极高的方法expensive_op,该方法仅需执行一次,且其生成的属性需对所有子类可用。当前实例化B和C时都会执行A中的expensive_op,我希望仅在调用b=B()时执行该方法,且A不会被直接实例化。此外,我还希望能在子类中修改父类的属性,例如B类中的modify方法实现的功能。

尝试的代码
class A:
  def __init__(self):
    self.something = None
  def expensive_op(self):
    if self.something is not None:
      self.something = #something ugly and expensive
执行结果
b=B()
c=C()
b.expensive_op(3)
print(b.something)
>>> 3
print(c.something is None)
>>> True
疑问

请问我哪里理解错了?该如何实现需求?

内容的提问来源于stack exchange,提问作者lorenzo_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 14:18:16