Hello! 欢迎来到小浪资源网!



如何用简洁方法自定义Python字典数据类型?


如何用简洁方法自定义Python字典数据类型?

想要自定义字典数据类型,考虑以下简洁方法:

利用星号(*)语法,可以直接将字典数据传递给 @dataclass 装饰器:

@dataclass class abc:     a: int  test([abc(**{'a': 1}), abc(**{'a': 2})])

实现 from_dict 类方法,通过字典数据创建对象实例,然后再传递给 @dataclass:

@dataclass class abc:     a: int      @classmethod     def from_dict(cls, data):         return cls(**data)  test([abc.from_dict({'a': 1}), abc.from_dict({'a': 2})])

使用 typeddict,它创建了类型检查的字典类型:

立即学习Python免费学习笔记(深入)”;

from typing import TypedDict, List  class ABC(TypedDict):     a: int  def test(params: List[ABC]):     print(params)  test([{'a': 1}, {'a': 2}])

相关阅读

==========================
Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/www.xlycwl.com/wp-content/plugins/wp-autopost-pro/wp-autopost-function.php on line 9730

Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/www.xlycwl.com/wp-content/plugins/wp-autopost-pro/wp-autopost-function.php on line 9733

Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/www.xlycwl.com/wp-content/plugins/wp-autopost-pro/wp-autopost-function.php on line 9736