zoukankan      html  css  js  c++  java
  • python namedtuple

    python standard library介绍了一个叫做namedtuple的东西:

    __author__ = 'sfesly'
    import collections
    Person = collections.namedtuple('Person', 'name age gender')
    print('type of Person: %s' % (type(Person)))
    bob = Person(name='Bob', age =30, gender='male')
    print('
    Representation:%s' % (str(bob)))
    jane = Person(name='Jane', age=29,gender='female')
    print('
    Field by name:%s' % (jane.name))
    for p in [bob, jane]:
        print ('%s is a %d year old %s' % p)
    print(bob[2])
    

     这段代码的两点在type(Person),输出为:

      type of Person: <class 'type'>

    也就是相当于添加了这样一段定义:

    class Person(object):

       def __init__(self, name, age, gender):

          self.name = name

          self.age = age

          self.gender = gender

    Person是一个动态生成的类型。

    最重要的是,除了像结构体那样可以按field访问之外,它还能像一般的元组那样按索引访问。Person还是元组的子类。

    对于习惯C语言中结构体童鞋来说,这个可以说是最好的替代品!

  • 相关阅读:
    cocos2d游戏jsc文件格式解密,SpideMonkey大冒险
    抖音下载短视频去水印方法
    Metaspliot技术
    WAF bypass
    博客园美化
    Redis未授权访问利用
    网站后台getshell
    OpenVAS
    跨站脚本攻击与防御总结
    相同浏览器同一浏览器多用户登录问题
  • 原文地址:https://www.cnblogs.com/hustxujinkang/p/4643652.html
Copyright © 2011-2022 走看看