首页 > 解决方案 > Python为一个类封装数据

问题描述

我有两个继承自 A 的 Python 类 A 和 B。在运行时,我只有一个 A 类的实例,但有许多 B 类的实例。

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

  def _init2 (self, AA)
    self.a = AA.a

class B(A):
  def __init__(self, AA, b):
    super()._init2(AA)
    self.b = b

AA = A(0)
BB = B(AA, 1)

这是写它的好方法吗?好像很丑...

标签: python

解决方案


删除init2并仅使用__init__. 两者兼有是令人困惑和不自然的。

class A:
  def __init__(self, obj):
    # I believe that this is what you tried to achieve
    if isinstance(obj, type(self)):
        self.a = obj.a    
    else:
        self.a = obj

class B(A):
  def __init__(self, A, b):
    super().__init__(A)
    self.b = b

顺便说一句,这里调用的东西太多了AAindef __init__(self, A, b):很可能不是指您所A期望的。


推荐阅读