Python的collections之namedtuple的使用及其优势

类实现:

class User:
def __init__(self, name, age, height):
self.name = name
self.age = age
self.height = height user = User(name="baoshan", age=31, height=170)
print(user.name, user.age, user.height)

namedtuple实现

方式1:

from collections import namedtuple

User = namedtuple("User", ["name", "age", "height"])
user = User(name="baoshan", age=31, height=170)
print(user.name, user.age, user.height)

方式2:

from collections import namedtuple

User = namedtuple("User", ["name", "age", "height"])
user_tuple = ("baoshan", 31, 170)
user = User(*user_tuple)
print(user.name, user.age, user.height)

namedtuple的优势

# namedtuple直接可以创建一个类
# 优势1: 代码简洁
# 优势2: 内存小,效率高 数据处理方面很有优势
user_info_dict = user._asdict()
print(user_info_dict) # namedtuple可以转换为dict
name, age, *others = user
print(name, age, *others) # namedtuple可以拆包
上一篇:不可不知的Python模块: collections


下一篇:python 模块和包深度学习理解