Is it possible only to declare a variable without assigning any value in Python?

后端 未结 14 1847
暖寄归人
暖寄归人 2020-11-30 17:26

Is it possible to declare a variable in Python, like so?:

var

so that it initialized to None? It seems like Python allows this, but as soon

14条回答
  •  攒了一身酷
    2020-11-30 17:57

    In Python 3.6+ you could use Variable Annotations for this:

    https://www.python.org/dev/peps/pep-0526/#abstract

    PEP 484 introduced type hints, a.k.a. type annotations. While its main focus was function annotations, it also introduced the notion of type comments to annotate variables:

    # 'captain' is a string (Note: initial value is a problem)
    captain = ...  # type: str
    

    PEP 526 aims at adding syntax to Python for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments:

    captain: str  # Note: no initial value!
    

    It seems to be more directly in line with what you were asking "Is it possible only to declare a variable without assigning any value in Python?"

提交回复
热议问题