【问题标题】:Instantiate parent class only once when calling from two child classes从两个子类调用时仅实例化一次父类
【发布时间】:2021-10-22 03:50:48
【问题描述】:

我想知道是否有一种方法,我们可以在从一个子类调用时只实例化一个类,并以某种方式将其缓存并用于第二个子类,而无需实例化父类。

class A:
   def __init__(self):
      #some huge data stored in self parameters.
class B:
   def __init__(self):
      A.__init__(self)
class C:
   def __init__(self):
      A.__init(self)

所以 B 类和 C 类都使用 A 类作为父类,并且 A 类初始化了大量数据,B 类和 C 类都可以使用这些数据。所以我在这里想要实现的是当我实例化 B 类时例如,它实例化类 A 并将所有数据加载到内存中并缓存实例,因此当我立即实例化类 C 时,它会查找该类的现有实例而不再次实例化它。

【问题讨论】:

标签: python-3.x python-class


【解决方案1】:

如何在 B 中实例化 A 并提供一种将数据从 B 传输到外部的方法?见下文:


class A:
   def __init__(self):
      self.huge_data = [.....]

   def data(self):
      return self.huge_data

class B:
   def __init__(self):
      self.a = A()

   def pass_data(self)
      return a.data()

class C:
   def __init__(self):
      A.__init(self)

一旦你实例化了B,你就可以使用该方法来访问数据了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2015-09-18
    • 2014-04-04
    相关资源
    最近更新 更多