从父 class 的构造函数继承一些但不是所有参数? Python
Inherit SOME but not all arguments from parent class's constructor? Python
假设我有父 class P
class P(object):
def __init__(self, a, b, c):
self._a = a
self._b = b
self._c = c
如果创建另一个 class C,它是 P 的子 class,是否可以继承 P 的一些参数但不是全部(假设我只想要参数 a、c 来自class P 将传递给 C)。我知道这是一个奇怪的问题,我不知道是否有适用于此的问题,但我似乎找不到答案。提前致谢!
据我所知,唯一好的方法是执行以下操作:
class P:
def __init__(self, a, b, c):
self._a = a
self._b = b
self._c = c
class C(P):
def __init__(self, a, b, c):
super(C, self).__init__(a, b, c)
self._b = b
本质上,您调用 superclass 构造函数来定义所有值,然后在 child class构造函数。
或者,如果你不想让 self._b
成为 class C
中的一个东西,你也可以在 [=15] 之后做 del self._b
=] 调用将其完全删除。
不过,总的来说,child class not 的某些字段 parent class 有,因为代码的其他部分可能依赖于该字段。
假设我有父 class P
class P(object):
def __init__(self, a, b, c):
self._a = a
self._b = b
self._c = c
如果创建另一个 class C,它是 P 的子 class,是否可以继承 P 的一些参数但不是全部(假设我只想要参数 a、c 来自class P 将传递给 C)。我知道这是一个奇怪的问题,我不知道是否有适用于此的问题,但我似乎找不到答案。提前致谢!
据我所知,唯一好的方法是执行以下操作:
class P:
def __init__(self, a, b, c):
self._a = a
self._b = b
self._c = c
class C(P):
def __init__(self, a, b, c):
super(C, self).__init__(a, b, c)
self._b = b
本质上,您调用 superclass 构造函数来定义所有值,然后在 child class构造函数。
或者,如果你不想让 self._b
成为 class C
中的一个东西,你也可以在 [=15] 之后做 del self._b
=] 调用将其完全删除。
不过,总的来说,child class not 的某些字段 parent class 有,因为代码的其他部分可能依赖于该字段。