zoukankan      html  css  js  c++  java
  • namedtuple简单实用

    namedtuple的好处是简单易用,并且在使用变量时,可以通过 对象.属性 的格式,获取值,这和普通实例化出来的类的实例如出一辙,可以相当清楚的看出到底是用了哪个属性。

    譬如一个类:

    class Person():
        def __init__(self,name,age):
            self.name = name
            self.age = age
    
        def __str__(self):
            return f"Person(name='{self.name}', age={self.age})"
    
    p = Person('wang',23)
    print(p.name,p.age)
    print(p)
    print(p.__class__)
    

    对比 namedtuple:

    from collections import namedtuple as nt
    
    people = nt("Person",["name","age"])
    p = people("wang",23)
    print(p.name,p.age)
    print(p)
    print(p.__class__)
    

    从两段代码的执行结果来看,两者是相同的。但是 namedtuple 使用了更少的代码,并且它还支持其他操作:

    p = people("wang",23)
    p = people(name='zhang',age=22)
    p = people(*['wang',25])
    p = people(**{"name":'A', 'age':33})
    
    # 替换旧值
    p = p._replace(age='aaa')
    print(p)
    
    # 转换为字典
    d = p._asdict()
    print(d)
    
    # 索引取值
    print(p[0], p[1])
    a, b = p
    print(a, b)
    

    namedtuple 的好处,体现在索引取值中。当一个元组很长,用索引取值,在后续的代码中,很难看出某个索引代表什么意思。 譬如:

    from collections import namedtuple as nt
    
    people = nt("Person",["name","age","weight","hight"])
    
    zhang = people('zhang',23,80,170)
    
    # 不清楚索引代表的值
    if zhang[2] < 90:
        print('体重小于90')
    
    # 取值很明确
    if zhang.weight < 90:
        print("small than 90")
    
    
  • 相关阅读:
    Seconds_Behind_Master的计算
    innnodb 线程在做什么?
    Mysql Join_buffer_size的使用原理
    C 实现位图排序
    C 内存池的实现
    C实现队列
    mysqld执行的函数栈
    Source Insight的基本用法
    MySQL高性能以及高安全测试
    【设计篇】状态与策略
  • 原文地址:https://www.cnblogs.com/wztshine/p/15293756.html
Copyright © 2011-2022 走看看