【问题标题】:How to hint that a variable is a class inheriting from another class?如何暗示变量是从另一个类继承的类?
【发布时间】:2018-11-22 03:30:44
【问题描述】:

考虑这个人为的代码sn-p:

class Fooer():
    def __init__(self, *args, **kwargs):
        # do things

    def foo(self) -> int:
        # do more things

def foo(fooer, *args, **kwargs) -> int:
    return x(*args, **kwargs).foo()

我想暗示foo()fooer 参数应该是Fooer 的子类。它不是Fooer 的实例,它要么是Fooer 本身,要么是其子类。我能想到的最好的是

def foo(fooer: type, *args, **kwargs) -> int

这不够具体。

我怎样才能更好地暗示这一点?

【问题讨论】:

  • 子类化不好。不要在你的 API 中鼓励它。
  • @Jean-PaulCalderone 我正在尝试清理现有的代码库。这主要是为了我的理智和我队友的理智。尽管最近出现了(合理的,但夸大的)反继承模因,但仍有许多有效和/或实际的理由使用子类化。
  • @chepner fooer 不是Fooer 的实例,它是一个类,既可以是Fooer 本身,也可以是其子类
  • 啊,这是我错过的一个关键细节。
  • 如果我正确阅读 PEP-484,我认为它是 fooer: Type[Fooer]

标签: python python-3.x type-hinting mypy


【解决方案1】:

从 PEP-484 (The type of class objects) 开始,解决方案是使用 Type[C] 来指示 C 的子类,其中 C 是由您的基类限定的类型 var。

F = TypeVar('F', bound=Fooer)

def foo(fooer: Type[F], *args,**kwargs) -> int:
    ...

(公平地说,我不太明白在此处使用 TypeVar(如 PEP-484 所示)与在 @e.s. 的答案中使用类本身之间的区别。)

【讨论】:

    【解决方案2】:

    typing 中有一个Type

    from typing import Type
    
    class A(object):
        def __init__(self, thing):
            self.thing = thing
    
    class B(A):
        pass
    
    def make_it(a_class: Type[A]):
        return a_class(3)
    
    make_it(B)  # type checks ok
    make_it(str)  # type checks complaining
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多