首页 > 解决方案 > 子类化字符串并让 MyPy 开心

问题描述

如何使此代码成功运行并通过 mypy 检查?

from datetime import datetime

class TimeStamp(str):
    """ID with a short form and a long form."""
    
    def __new__(cls, datetime) -> TimeStamp:
        short = str(datetime.timestamp())
        long = datetime.strftime("%Y-%m-%d %H:%M:%S")
        obj = str.__new__(cls, short)
        obj.short = short
        obj.long = long
        return obj

now = TimeStamp(datetime.now())
print(now)
print(now.long)

当前mypy untitled1.py导致以下错误:

untitled1.py:10: error: "TimeStamp" has no attribute "short"
untitled1.py:11: error: "TimeStamp" has no attribute "long"
untitled1.py:16: error: "TimeStamp" has no attribute "long"
Found 3 errors in 1 file (checked 1 source file)

标签: pythonmypy

解决方案


如果我省略了返回类型,MyPy 会非常高兴__new__。但是我必须为对象属性进行类型注释。所以解决方案如下所示:

from datetime import datetime

class TimeStamp(str):
    """ID with a short form and a long form."""
    
    short: str
    long: str
    
    def __new__(cls, datetime):
        short = str(datetime.timestamp())
        long = datetime.strftime("%Y-%m-%d %H:%M:%S")
        obj = str.__new__(cls, short)
        obj.short = short
        obj.long = long
        return obj

now = TimeStamp(datetime.now())
print(now)
print(now.long)

这通过了 MyPy 检查并且可以运行。


推荐阅读