基于参数数量的Python方法重载?

1 投票
2 回答
1172 浏览
提问于 2025-04-16 02:23

如果我在没有任何参数的情况下调用 QApplication 的 init 方法,我会得到

TypeError: arguments did not match any overloaded call:
  QApplication(list-of-str): not enough arguments
  QApplication(list-of-str, bool): not enough arguments
  QApplication(list-of-str, QApplication.Type): not enough arguments
  QApplication(Display, int visual=0, int colormap=0): not enough arguments
  QApplication(Display, list-of-str, int visual=0, int cmap=0): not enough arguments

这真有意思!我该怎么写一个这样的类呢?我的意思是,我见过的所有关于这种函数重载的技巧都没有涉及到明确的参数签名。

2 个回答

0

很有可能它的初始化方法就是用 __init__(self, *args, **kwargs) 这个形式,然后自己对 args 列表和 kwargs 字典进行一些检查。

3

TypeError 只是另一种异常(错误)。你可以使用 *args 和 **kwargs 来接收参数,检查这些参数,然后自己抛出一个 TypeError,指定要显示的文本,比如列出预期的调用方式。

说到这里,PyQt 是一堆 .pyd 文件,也就是用 C 或 C++ 写的本地 Python 扩展(使用 Boost::Python)。据我所知,后者至少支持“真正的”重载。

无论如何,除非你有非常好的理由,否则不应该这样做。Python 是一种鸭子类型(duck-typed)语言,应该接受这一点。

撰写回答