我有一個配置 ini 檔案,如下所示:
[user]
name=john
sex=male
age=19
income=2345.99
我有一個User用__init__下面的建構式呼叫的 Python 類:
class User:
def __init__(self, name: str, sex: str, age: int, income: float):
self.__name = name
self.__sex = sex
self.__age = age
self.__income = income
當我使用ConfigParser讀取ini檔案并將configparser字典傳遞給User建構式時,字典中的值是字串。
config = ConfigParser()
config.read('test.ini')
user = User(**config["user"])
ConfigParser有像getfloat, getint, getboolean.這樣的方法 我可以使用這些方法并為每個引數獲取正確的資料型別。
但是,這需要我將每個引數傳遞給User建構式。每當我需要為User建構式添加/洗掉引數時,這可能會很麻煩
無論如何user = User(**config["user"])在建構式和配置ConfigParser中使用將值轉換為正確的資料型別?
謝謝。
uj5u.com熱心網友回復:
如果您使用pydantic 之類的東西,這將變得微不足道:
import pydantic
import configparser
class User(pydantic.BaseModel):
name: str
sex: str
age: int
income: float
config = configparser.ConfigParser()
with open("config.ini") as fd:
config.read_file(fd)
user = User(**config["user"])
此時,組態檔中的字串值已轉換為適當的資料型別:
>>> type(user.income)
<class 'float'>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453471.html
標籤:Python python-3.x 字典 配置解析器
