python 自定义类转字符串
时间: 2023-09-23 11:05:08 浏览: 176
自定义字符串
要将Python自定义类转换为字符串,可以使用JSON模块的dumps()方法。首先,需要在自定义类中实现一个to_dict()方法,该方法将自定义类的属性转换为字典。然后,使用dumps()方法将字典转换为JSON字符串。
以下是将自定义类Person转换为字符串的示例代码:
```python
import json
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def to_dict(self):
return {
'name': self.name,
'age': self.age
}
person = Person('John', 25)
json_string = json.dumps(person.to_dict())
print(json_string)
```
这样,person对象就会被转换为JSON字符串,并且可以在需要的地方使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [Python自定义对象转json、json转Python自定义对象](https://blog.csdn.net/weixin_33011357/article/details/113676339)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* [Python中自定义类对象json字符串化的方法](https://blog.csdn.net/weixin_30364031/article/details/116171706)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文