python - 子类化字符串并让 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)
解决方案
如果我省略了返回类型,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 检查并且可以运行。
推荐阅读
- android - Android 联系人选取器在不同版本中具有不同的行为
- vega-lite - 如何在 Vega-lite 变换中使用条件语句
- javascript - 未处理的 Promise Rejection: TypeError: undefined is not an object (evalating 'data.date')
- javascript - 如何在桌面浏览器中从触控板上捕获捏缩放手势(并防止默认)?
- c# - 具有大量可选但必要参数的重构类
- post - 将带有正文数据的发布请求发送到 symfony 控制器我在 $request 中一无所获
- angular - 如何在 nz-autocomplete 上设置默认初始值
- serial-port - VB.Net SerialPort1.DataReceived 事件理解
- php - 自定义 wp api 端点中的显示
- java - 如何建议 maven-jaxb2-plugin 在两个地方使用同一个类?