在Python中,子类的__init__中是否合适重写父类的参数?

1 投票
2 回答
52 浏览
提问于 2025-04-12 18:00

请看下面的代码示例。

我的开发环境(IDE)把“do_something_special”标记为未解决的属性引用,意思是它找不到这个属性,属于“ParentAttribute”类。

这让我怀疑这可能是一种反模式,也就是说我应该换个方法来实现同样的目标(创建更复杂的特定模式实例,而不重复代码)。

那么,怎么做才是最佳实践呢?

这里有一个简单的例子。我本来希望我的开发环境能把这个当作有效的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()

2 个回答

0

你可以在 Child 里给 x 添加一个类型。

class Child(Parent):

    x: ChildAttribute

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

不过,如果有东西把 x 赋值为 ParentAttribute,这样做可能就不安全了。例如:

child = Child(ChildAttribute())
parent: Parent = child
parent.x = ParentAttribute()

# Runtime error, not caught by type checker
child.x.do_something_special()

这可能对你来说是一个可以接受的类型安全级别,但根据你的需求,你可能想通过设置器和获取器来保护 x 的变化,或者甚至把 x 的类型定义为 ChildAttribute | ParentAttribute,每次访问 x 中特有于 ChildAttribute 的属性时都使用类型保护。

撰写回答