V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
ves
V2EX  ›  Python

Python 类中类型提示使用“定义类”提示未定义

  •  
  •   ves · 2021-09-09 20:54:00 +08:00 · 1667 次点击
    这是一个创建于 932 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如图,最后那个 Card 提示未定义,这有什么解决办法吗

    10 条回复    2021-09-10 21:36:05 +08:00
    ves
        1
    ves  
    OP
       2021-09-09 21:19:30 +08:00
    ClericPy
        2
    ClericPy  
       2021-09-09 22:45:50 +08:00
    加上引号
    ipwx
        3
    ipwx  
       2021-09-10 01:07:52 +08:00   ❤️ 2
    def create_from_shortstr(cls, ss: str) -> 'Card':


    不过这种我建议不要加 -> Card,因为其实是 classmethod 返回的是 cls()。也不要用 Generic[T],这样很麻烦。
    Trim21
        4
    Trim21  
       2021-09-10 07:55:20 +08:00
    这里不应该用 Generic[T],可以月 TypeVar

    Trim21
        5
    Trim21  
       2021-09-10 07:57:52 +08:00
    你这个方法在类型上返回的也不是 Card 。如果 Card 是 List[str],那你这个方法的返回值就是 str
    Trim21
        6
    Trim21  
       2021-09-10 08:03:06 +08:00
    @Trim21 #5 这个是说你在#1 的写的 Generic[T]和 T
    Acebiu
        7
    Acebiu  
       2021-09-10 08:41:59 +08:00
    如果不需要兼容 3.7 以下的版本的话也可以使用

    ```python
    from __future__ import annotations
    ```

    https://docs.python.org/3/library/__future__.html
    popil1987
        8
    popil1987  
       2021-09-10 08:44:41 +08:00
    可以把 create_from_shortstr 单独作为一个“工厂函数”,让它:
    返回 Card 类本身
    返回 Card 对象,根据传入参数
    返回 Card 类,使用 Type 对类进行构造
    2i2Re2PLMaDnghL
        9
    2i2Re2PLMaDnghL  
       2021-09-10 09:38:22 +08:00
    推荐 ponylang 的,可以定义多个不同构造器函数。

    怎么就没有一个 @constructor 或者 @initiator 修饰器呢,这样函数的签名也跟 __init__ 一致。
    ves
        10
    ves  
    OP
       2021-09-10 21:36:05 +08:00
    @ipwx 感谢,不加是正解。

    正因为是 classmethod 返回的,而 classmethod 使用的是泛型,所以 IDE 也能正确提示。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2840 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 12:56 · PVG 20:56 · LAX 05:56 · JFK 08:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.