从Python 3.7开始,有一种称为数据类的东西:
from dataclasses import dataclass
@dataclass
class Foo:
x: str
Run Code Online (Sandbox Code Playgroud)
但是,以下失败:
>>> import json
>>> foo = Foo(x="bar")
>>> json.dumps(foo)
TypeError: Object of type Foo is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
如何将json.dumps()编码实例Foo转换为json 对象?
我有一个dataclass对象,其中包含嵌套的数据类对象.但是,当我创建主对象时,嵌套对象变成了字典:
@dataclass
class One:
f_one: int
@dataclass
class One:
f_one: int
f_two: str
@dataclass
class Two:
f_three: str
f_four: One
data = {'f_three': 'three', 'f_four': {'f_one': 1, 'f_two': 'two'}}
two = Two(**data)
two
Two(f_three='three', f_four={'f_one': 1, 'f_two': 'two'})
obj = {'f_three': 'three', 'f_four': One(**{'f_one': 1, 'f_two': 'two'})}
two_2 = Two(**data)
two_2
Two(f_three='three', f_four={'f_one': 1, 'f_two': 'two'})
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我试图将所有数据作为字典传递,但我没有得到预期的结果.然后我尝试首先构造嵌套对象并将其传递给对象构造函数,但我得到了相同的结果.
理想情况下,我想构建我的对象来得到这样的东西:
Two(f_three='three', f_four=One(f_one=1, f_two='two'))
Run Code Online (Sandbox Code Playgroud)
除了手动将嵌套字典转换为相应的数据类对象,每当访问对象属性时,有没有办法实现其他目的?
提前致谢.
我们已经研究了几个小时了,没有运气,有很多方法可以在 Python 中序列化和反序列化对象,但我们需要一个简单而标准的尊重类型的方法,例如:
from typings import List, NamedTuple
class Address(object):
city:str
postcode:str
class Person(NamedTuple):
name:str
addresses:List[Address]
Run Code Online (Sandbox Code Playgroud)
我的问题非常简单,我正在寻找一种标准的方式来转换为 JSON,而无需为每个类编写序列化/反序列化代码,例如:
json = '{ "name": "John", "addresses": [{ "postcode": "EC2 2FA", "city": "London" }, { "city": "Paris", "postcode": "545887", "extra_attribute": "" }]}'
Run Code Online (Sandbox Code Playgroud)
我需要一种方法:
p= magic(json, Person) # or something similar
print(type(p)) # should print Person
for a in p.addresses:
print(type(a)) # prints Address
print(a.city) # should print London then Paris
json2 = unmagic(p)
print(json2 == json) # prints true (probably there will be …Run Code Online (Sandbox Code Playgroud) 这是我在python 3.6中的代码
class A(object)
def __init__(self, a: str):
self._int_a: int = int(a) # desired composition
def get_int_a(self) -> int:
return self._int_a
Run Code Online (Sandbox Code Playgroud)
我想重写这段代码python 3.7,我如何self._int_a: int = int(a)用dataclasses模块初始化?
我知道我可以做类似的事情,但我不知道如何初始化_a: int = int(a)或类似。
from dataclasses import dataclass
@dataclass
class A(object):
_a: int = int(a) # i want to get initialized `int` object here
def get_int_a(self) -> int:
return self._a
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的想法和建议。