我可以在子类的构造函数中为 kwarg 添加特异性吗?

Can I add specificity to a kwarg in a subclass' constructor?

我试图让 PyCharm 了解我的基本控制器 class 的子 class 只接受特定类型的小部件。

最小示例:

import tkinter as tk


class BaseWidgetController:
    def __init__(self, parent: 'tk.Widget'): # Parent is always __some__ kind of widget
        self._parent = parent


class EntryWidgetController(BaseWidgetController):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._parent: 'tk.Entry' # On this class, I want Pycharm to understand _parent is only ever an Entry (a subclass of tk.Widget), but even adding this line doesn't change its mind.

    def say_type(self) -> None:
        print(type(self._parent)) # PyCharm still thinks _parent is a tk.Widget


ew = EntryWidgetController(parent=tk.Frame())
ew.say_type()  # Obviously this works fine at runtime.

如果您想限制 EntryWidgetController 使其只接受 tk.Entry 或子类,修复方法相当简单 - 只需执行

class EntryWidgetController(BaseWidgetController):
    def __init__(self, parent: 'tk.Entry', **kwargs):
        super().__init__(parent=parent, **kwargs)

那样

ew = EntryWidgetController(parent=tk.Frame())

会让PyCharm抱怨Expected type 'Entry', got 'Frame' instead