给定一个子父结构如下:
class Parent:
def __init__(self, param1=1, param2=2, param3=3, param4=4):
"""
Parent docstring here
:param param1: param1 stuff
:param param2: param2 stuff
:param param3: param3 stuff
:param param4: param4 stuff
"""
self.param1 = param1
self.param2 = param2
self.param3 = param3
self.param4 = param4
class Child(Parent):
def __init__(self, param1=1, param2=2, param3=3, param4=4,
child_param1='a', child_param2='b', child_param3='c'):
"""
Child implementation of parent.
:param param1: do I need this again???
:param param2: do I need this again???
:param param3: do I need this again???
:param param4: do I need this again???
:param child_param1: child parameter 1
:param child_param2: child parameter 2
:param child_param3: child parameter 3
"""
super().__init__(param1, param2, param3, param4)
self.child_param3 = child_param3
self.child_param1 = child_param1
self.child_param2 = child_param2
在不重复父级的文档字符串和每个参数的情况下实现子项的正确方法是什么?我希望参数描述继承自父级。我也不想每次从父级继承时都重新指定默认值。我可以这样做,但这似乎不是正确的方法:
class Child(Parent):
def __init__(self, child_param1='a', child_param2='b', child_param3='c', **parent_args):
super(**parent_args)
# rest of the code goes here...
您不能从父级继承默认值,但您可以使用"特殊(唯一("默认值,然后使用它来设置"真实"默认值。 例如
DEFAULT = object()
class Vehicle:
DEFAULT_WHEELS = 4
def __init__(self, wheels=DEFAULT):
if wheels is DEFAULT:
wheels = self.DEFAULT_WHEELS
self.wheels = wheels
class Car(Vehicle):
DEFAULT_COLOUR = "Red"
def __init__(self, colour=DEFAULT, **kwargs):
super().__init__(**kwargs)
if colour is DEFAULT:
colour = self.DEFAULT_COLOUR
self.colour = colour
# You can also use the class-level default to modify the
# defaults without having to re-write the init:
class Tricycle(Vehicle):
DEFAULT_WHEELS = 3