ValueError:可变默认值< class' dict'>对于场标头,不允许:使用Default_factory
我正在尝试使用新的Python的功能(Dataclasses)。我正在尝试初始化变量,并且会遇到错误:
raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'dict'> for field headers is not allowed: use default_factory
我的代码:
@dataclass
class Application():
__config = ConfigParser()
__config.read('mydb.ini')
__host: str = __config.get('db','dbhost')
__user: str = __config.get('db','dbuser')
__password: str = __config.get('db','dbpw')
__database: str = __config.get('db','database')
url: str = "https://xxxx.domain.com/"
headers: str = {'X-ApiKeys':'accessKey=xxxxxxx;secretKey=xxxxx','Content-Type': 'application/json'}
def main(self):
print(self.__host,self.__user,self.__password, self.__database)
app = Application()
if __name__=="__main__":
app.main()
初始化字典的正确方法是什么?
I am trying to get used with new python's features (dataclasses). I am trying to initialize variables and I get error:
raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'dict'> for field headers is not allowed: use default_factory
My code:
@dataclass
class Application():
__config = ConfigParser()
__config.read('mydb.ini')
__host: str = __config.get('db','dbhost')
__user: str = __config.get('db','dbuser')
__password: str = __config.get('db','dbpw')
__database: str = __config.get('db','database')
url: str = "https://xxxx.domain.com/"
headers: str = {'X-ApiKeys':'accessKey=xxxxxxx;secretKey=xxxxx','Content-Type': 'application/json'}
def main(self):
print(self.__host,self.__user,self.__password, self.__database)
app = Application()
if __name__=="__main__":
app.main()
What's the proper way to initialize dictionaries?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
数据级有一些有用的东西来定义复杂字段。您需要的一个称为 field 。这个有参数
default_factory
需要接收可召唤,并且在某些地方lambda
可以进行救援。因此,使用上面的代码看起来像(仅与DICE的一部分):Dataclasses have a few useful things for defining complex fields. The one that you need is called field. This one has the argument
default_factory
that needs to receive callable, and there is wherelambda
comes to the rescue. So using this above, code that will work looks like (just part with dict):