小编Kan*_*shk的帖子

类型暗示返回 self 的类方法的返回值?

正如问题所描述的,我想输入提示selfreturn ,例如:

class A:
    def foo(self) -> [what goes here?]:
        # do something
        return self
Run Code Online (Sandbox Code Playgroud)

我已经尝试过的事情:

  1. 将其注释为Afrom __future__ import annotations在顶部添加):这意味着该方法返回一个实例化A()对象,但不一定self
  2. 将其注释为Type[A](adding from typing import Type):这意味着该方法返回的是返回一个未实例化的A,它与 相差甚远self
  3. 注释为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...谢谢

python python-typing

9
推荐指数
1
解决办法
5036
查看次数

如何将 json 文件转换为 python 类?

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添加新键时都添加属性?

python oop json python-dataclasses python-class

7
推荐指数
2
解决办法
2万
查看次数