正如问题所描述的,我想输入提示self
return ,例如:
class A:
def foo(self) -> [what goes here?]:
# do something
return self
Run Code Online (Sandbox Code Playgroud)
我已经尝试过的事情:
A
(from __future__ import annotations
在顶部添加):这意味着该方法返回一个实例化A()
对象,但不一定self
。Type[A]
(adding from typing import Type
):这意味着该方法返回的是返回一个未实例化的A
,它与 相差甚远self
。Self
(添加from typing_extensions import Self
):mypy 给出错误:
Variable "typing_extensions.Self" is not valid as a type [valid-type]mypy(error)
可能有帮助的事情foo
:将鼠标悬停在没有返回值注释的方法上,VScode
提示显示 - Self@A
,我不明白,但是,这绝对区分返回另一个实例化类A()
和返回self
...谢谢
h.json
考虑这个名为“我想将其转换为 python 数据类”的 json 文件。
{
"acc1":{
"email":"acc1@example.com",
"password":"acc1",
"name":"ACC1",
"salary":1
},
"acc2":{
"email":"acc2@example.com",
"password":"acc2",
"name":"ACC2",
"salary":2
}
}
Run Code Online (Sandbox Code Playgroud)
我可以使用替代构造函数来获取每个帐户,例如:
import json
from dataclasses import dataclass
@dataclass
class Account(object):
email:str
password:str
name:str
salary:int
@classmethod
def from_json(cls, json_key):
file = json.load(open("h.json"))
return cls(**file[json_key])
Run Code Online (Sandbox Code Playgroud)
但这仅限于数据类中定义的参数(电子邮件、姓名等)。
如果我要修改 json 以包含其他内容(例如年龄)怎么办?该脚本最终将返回一个TypeError
,特别是TypeError: __init__() got an unexpected keyword argument 'age'
.
有没有办法根据dict(json对象)的键动态调整类属性,这样我就不必每次向json添加新键时都添加属性?