@dataclass class InputExample: guid: str text_a: str text_b: Optional[str] = None label: Optional[str] = None def to_json_string(self): return json.dumps(dataclasses.asdict(self), indent=2) + "\n"
时间: 2024-04-17 22:24:34 浏览: 128
这段代码定义了一个名为`InputExample`的数据类(data class)。这个类使用`@dataclass`装饰器来简化定义。
`InputExample`类有四个属性:`guid`、`text_a`、`text_b`和`label`。其中,`guid`和`text_a`是必需的,而`text_b`和`label`是可选的。这些属性的类型都是字符串类型。
`to_json_string()`方法是一个实例方法,用于将`InputExample`对象转换为JSON格式的字符串。它使用`json.dumps()`函数将对象转换为字典形式(使用`dataclasses.asdict(self)`),然后使用`indent=2`参数设置缩进为2个空格,并在最后添加一个换行符。
通过调用`to_json_string()`方法,你可以将一个`InputExample`对象转换为JSON格式的字符串表示。例如:
```python
example = InputExample(guid="1", text_a="Hello", text_b="World", label="Positive")
json_string = example.to_json_string()
print(json_string)
```
输出结果为:
```
{
"guid": "1",
"text_a": "Hello",
"text_b": "World",
"label": "Positive"
}
```
这样可以方便地将对象序列化为JSON格式,并进行存储、传输等操作。请确保在使用这段代码之前已经导入了必要的库,如`dataclass`和`json`。
阅读全文
相关推荐


















