Python3 namedtuple详解

Python3 namedtuple详解

1. 用namedtuple可以创建一个类

from collections import namedtuple
User = namedtuple("User", ["name", "age", "height"]) # 第一个参数为类名,后面为参数
user = User(name="流川枫", age=29, height=175)
print(user.age, user.name)

2. 用法比较简单,只适合简单的类,不需要写大量class代码

3. 很省空间,用namedtuple生成的类少了很多内置的变量,比如__name__等

4. 将user表的数据全部取出然后加到一个列中

from collections import namedtuple

User = namedtuple("User", ["name", "age", "height"]) # 第一个参数为类名,后面为参数
user_tuple = ("流川枫", 21, 189)
user = User(*user_tuple)  # *user_tuple的作用就是将tuple解包
print(user.age, user.name, user.height)

5. 将namedtuple的类转化为一个dict:

from collections import namedtuple

User = namedtuple("User", ["name", "age", "height"]) # 第一个参数为类名,后面为参数
user_tuple = ("流川枫", 21, 189)
user = User(*user_tuple)
# 将user转换为一个字典OrderedDict([('name', '流川枫'), ('age', 21), ('height', 189)])
user_info_dict = user._asdict()

6. 因为namedtuple继承tuple,所以可以使用tuple的拆包功能

from collections import namedtuple

User = namedtuple("User", ["name", "age", "height"]) # 第一个参数为类名,后面为参数
user_tuple = ("流川枫", 21, 189)
user = User(*user_tuple)
name, age ,height = user
print(name, age, height)

你可能感兴趣的:(Python3)