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
teli
V2EX  ›  Python

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

  •  
  •   teli · 260 天前 · 1007 次点击
    这是一个创建于 260 天前的主题,其中的信息可能已经有所发展或是发生改变。

    一种实现如下:

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

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

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

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

    from typing import Tuple, List

    test_tup: Tuple[str, int, List[str]] = ('gfg', 1, ['is', 'best'])
    gosky
        3
    gosky  
       257 天前
    @coderluan 谢谢。可以拿到注解的参数类型
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   892 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:21 · PVG 05:21 · LAX 14:21 · JFK 17:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.