在编写类的接口的时候 如何指明参数类型为本类

class A():
    def __init__(self):
        pass

    def func(pra1:A):
        pass

这种情况下,在def func(par1:A) 中的A会报错,因为类A没有生成。请问这这种如何解决

Jason990420
最佳答案

For different versions of Python

  • In Python 3.6 or below, you should use a string - 'A'

    In PEP 484 – Type Hints

    Forward references

    When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

  • In Python 3.7 ~ 3.10, you can add statement from __future__ import annotations

  • In Python 3.11+, you can use from typing import Self, then use def func(pra1:Self):

1年前 评论
讨论数量: 2
Jason990420

For different versions of Python

  • In Python 3.6 or below, you should use a string - 'A'

    In PEP 484 – Type Hints

    Forward references

    When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

  • In Python 3.7 ~ 3.10, you can add statement from __future__ import annotations

  • In Python 3.11+, you can use from typing import Self, then use def func(pra1:Self):

1年前 评论

如一楼所说,加 双引号 就可以,或者 from __future__ import annotations。当然py311你还可以用 from typing import Self 代替。

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!