如何解决我可以在子类的构造函数中为 kwarg 添加特异性吗?
我试图让 PyCharm 了解我的基本控制器类的子类只采用特定类型的小部件。
最小示例:
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
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。