代码之家  ›  专栏  ›  技术社区  ›  voiDnyx

__call__方法参数类型推理是如何工作的?

  •  0
  • voiDnyx  · 技术社区  · 3 年前

    我在看 argparse python模块,并看到以下代码:

    class Action(_AttributeHolder):
        """Information about how to convert command line strings to Python objects.
        ...
        """
    
        def __init__(self,
                     option_strings,
                     dest,
                     nargs=None,
                     const=None,
                     default=None,
                     type=None,
                     choices=None,
                     required=False,
                     help=None,
                     metavar=None):
            self.option_strings = option_strings
            self.dest = dest
            self.nargs = nargs
            self.const = const
            self.default = default
            self.type = type
            self.choices = choices
            self.required = required
            self.help = help
            self.metavar = metavar
    
        def _get_kwargs(self):
            names = [
                'option_strings',
                'dest',
                'nargs',
                'const',
                'default',
                'type',
                'choices',
                'help',
                'metavar',
            ]
            return [(name, getattr(self, name)) for name in names]
    
        def __call__(self, parser, namespace, values, option_string=None):
            raise NotImplementedError(_('.__call__() not defined'))
    

    我使用pycharm作为IDE,如果我将鼠标悬停在 __call__ 方法我得到以下信息:

    enter image description here

    现在我通常使用类型暗示来赋予这个,但这里的暗示是在哪里完成的?

    有人能解释一下pycharm是如何知道这些论点的类型的吗?这些是从哪里来的?它们没有在类中定义 Action 也不是它的父级 _AttributeHolder (它本身是从对象派生的)也不在模块本身的任何地方。

    0 回复  |  直到 3 年前