【问题标题】:Python typehinting class methods with the class type [duplicate]具有类类型的Python类型提示类方法[重复]
【发布时间】:2021-09-13 22:10:57
【问题描述】:

我想知道是否有一种方法可以使用类作为类型来提示类的方法。

这个例子给出了一个 NameError 因为 Monomial 还没有定义:

class Monomial():
    def __init__(self, coef: int, grade: int) -> None:
        self.grade = grade
        self.coef = coef

    def product(self, other:Monomial) -> Monomial:
        return Monomial(self.coef*other.coef, self.grade+other.grade)

Typehinting 在外面完美地工作:

def product(firs:Monomial, other:Monomial) -> Monomial:
    return Monomial(first.coef*other.coef, first.grade+other.grade)

我想知道是否有一个关键字可以用来提示类型或其他解决方案。 这会很有用,因为我使用 mypy 作为类型检查器。

我知道我不能简单地说明类型,但我想找到一个解决方案,以便我可以检查类型。 在此先感谢:)

【问题讨论】:

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


    【解决方案1】:

    您必须将“Monomial”的前向引用放在这样的引号中:

    class MyClass:
        def doit(self) -> 'MyClass':
            pass
    
    

    详情请见https://www.python.org/dev/peps/pep-0484/#forward-references

    【讨论】:

      猜你喜欢
      • 2017-01-03
      • 1970-01-01
      • 2016-01-27
      • 2020-11-23
      • 2020-10-27
      • 2017-04-29
      • 2014-08-15
      • 1970-01-01
      相关资源
      最近更新 更多