【发布时间】:2018-07-05 00:36:51
【问题描述】:
我想从父类创建一个子类。这是为了减少代码中的冗余。例如,
class Parent():
def __init__(self, a, b, c, d, e, f, g):
self.a = a
self.b = b
...
self.g = g
class Child1(Parent):
def __init__(self, a, b, c, d, e, f, g, h, i, j, k):
super().__init__(a, b, c d, e, f, g)
self.i = i
self.j = j
self.k = k
class Child2(Parent):
def __init__(self, a, b, c, d, e, f, g, h, x, y, z):
super().__init__(a, b, c d, e, f, g)
self.x = x
self.y = y
self.z = z
我不想一次又一次地为所有子类传递参数。有没有办法让 Child1 和 Child2 从 Parent 类?
我有 30 多个参数和许多子类。写出所有参数似乎非常多余。此外,它们都与父母共享相同的参数。
【问题讨论】:
-
定义子类时必须指定父类:
Child1(Parent). -
@DyZ 啊是的,这是一个错字
-
如果你有 30+ 个参数,那你的代码设计肯定有问题。你考虑过传字典吗?
-
嗯,我需要为深度学习调整一堆超参数...
标签: python class inheritance