社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python将属性保留为未赋值,并使用省略号或None+float类型提示

Intrastellar Explorer • 5 年前 • 1477 次点击  

我想声明一个实例属性,类型暗示为 float ,初始化时不分配值。该值是在运行时、实例初始化后(也称为 __init__ ).

this answer ,我可以将值设置为 None . 但是,我的IDE( PyCharm PyTypeChecker 旗帜,说 Expected type 'float', got type 'None' instead .

我发现如果将值设置为省略号(建议 this answer ),aka值= ... ,PyCharm不再抱怨了。

这里的最佳做法是什么? ... ?


示例代码

class SomeClass:

    def __init__(self):
        """Initialize with an unassigned value."""

        # PyCharm complains here
        self._unassigned_val = None  # type: float

        # PyCharm doesn't complain here
        self._unassigned_val2 = ...  # type: float

    def called_during_runtime(self) -> None:
        """This gets called after __init__ has run."""
        self._unassigned_val = 1.0
        self._unassigned_val2 = 1.0

在我的IDE中是什么样子的:

Sample Code In PyCharm


  • PyCharm社区版 2019.2.5
  • 3.6
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52970
 
1477 次点击  
文章 [ 1 ]  |  最新文章 5 年前