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:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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可以拆包