推荐学习书目
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
teli
V2EX  ›  Python

Python 如何获取 tuple 元素的类型?

  •  
  •   teli · Aug 11, 2023 · 1768 views
    This topic created in 1031 days ago, the information mentioned may be changed or developed.

    一种实现如下:

    test_tup = ('gfg', 1, ['is', 'best'])
    list(map(type, test_tup))
    

    该实现是获取元祖实例的每个元素的类型。

    但如果只是类型,比如(str,),还没赋值,怎么获取到里面的类型?

    3 replies    2023-08-14 17:35:46 +08:00
    xe2vherd
        1
    xe2vherd  
       Aug 11, 2023
    没赋值怎么来的类型,不知道你是不是想拿 type hint 里面的类型...
    coderluan
        2
    coderluan  
       Aug 11, 2023
    python 里面,本来就是赋值之后变量才确定类型,楼主你想创建个对象确定类型但是不赋值,可以使用类型注释:

    from typing import Tuple, List

    test_tup: Tuple[str, int, List[str]] = ('gfg', 1, ['is', 'best'])
    gosky
        3
    gosky  
       Aug 14, 2023
    @coderluan 谢谢。可以拿到注解的参数类型
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2821 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 09:20 · PVG 17:20 · LAX 02:20 · JFK 05:20
    ♥ Do have faith in what you're doing.