widgets.Input
widgets.Input
上存在的属性我如何告诉 python 类型系统这个 mixin 扩展了
widgets.Input
接口而不继承 widgets.Input
?
奖励: 我可以告诉类型系统这个 mixin 只能与
widgets.Input
的子类一起使用吗?
from django.forms import widgets
class MaskedWidgetMixin:
def format_value(self, value):
return ""
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs) # <--- super().get_context does not exist
context["widget"]["attrs"] = self.build_attrs(self.attrs, attrs, value) # <--- self.attrs does not exist
return context
def build_attrs(self, base_attrs, extra_attrs=None, value: str = ""):
attrs = super().build_attrs(base_attrs, extra_attrs) # <--- super().build_attrs does not exist
if value:
attrs.update({"placeholder": "* ENCRYPTED *", "required": False})
return attrs
class EncryptedTextInputWidget(MaskedWidgetMixin, widgets.TextInput):
pass
class EncryptedTextareaWidget(MaskedWidgetMixin, widgets.Textarea):
pass
如评论中所建议,我尝试定义一个
Protocol
.Protocol
.Protocol
定义了一个由扩展它的类实现的接口。
以下代码会产生这种类型的错误...
Class derives from one or more protocol classes but does not implement all required members
Member "attrs" is declared in protocol class "InputProtocol"
class InputProtocol(Protocol):
attrs: dict[str, Any]
def get_context(self, name, value, attrs) -> dict[str, dict[str, Any]]:
...
def build_attrs(self, base_attrs, extra_attrs=None) -> dict[str, Any]:
...
class MaskedWidgetMixin(InputProtocol):
...