在Python中的子类__init__中子类化父类的参数是否合适?

问题描述 投票:0回答:1

请参阅下面的代码示例。

我的 IDE 将“do_something_special”突出显示为“ParentAttribute”类的未解析属性引用“do_something_special”

这让我怀疑这是一种反模式,我应该做一些不同的事情来实现相同的目标(创建特定模式的更复杂的实例而不重复代码)。

实现这一目标的最佳实践是什么?

这是一个简单的例子。我希望我的 IDE 将其视为有效的 Python。

class ParentAttribute:

    def __init__(self):
        ...

class Parent:

    def __init__(self,
                 x: ParentAttribute
                 ):
        self.x = x


class ChildAttribute(ParentAttribute):

    def __init__(self):
        super().__init__()
        ...

    def do_something_special(self):
        ...

class Child(Parent):

    def __init__(self,
                 x: ChildAttribute
                 ):
        super().__init__(x=x)
        self.x.do_something_special()
python inheritance python-typing
1个回答
0
投票

通过在

x
中添加
Child
的类型来直接解决问题似乎是最好的。

class Child(Parent):

    x: ChildAttribute

    def __init__(self,
                 x: ChildAttribute
                 ):
        super().__init__(x=x)
        self.x.do_something_special()

Parent
仍然可以安全地将
x
视为
ParentAttribute
,因此您在
Parent
中进行类型检查仍然会很好。并且
Child
可以利用
ChildAttribute
ParentAttribute
提供的任何附加功能。

© www.soinside.com 2019 - 2024. All rights reserved.