zoukankan      html  css  js  c++  java
  • python-namedtuple使用

    https://www.cnblogs.com/chenlin163/p/7259061.html

    利用collections.namedtuple,可以方便的创建对象,

    import collections
     
    MyTupleClass = collections.namedtuple('MyTupleClass',['name', 'age', 'job'])
    obj = MyTupleClass("Tomsom",12,'Cooker')
    print(obj.name)
    print(obj.age)
    print(obj.job)
    #output:
    Tomsom
    12
    Cooker

            还可以直接创建属性串:

            Person=collections.namedtuple(‘Person’,'name age gender’)

            ’Person’是namedtuple的名称,’name age gender’字符串中三个用空格隔开的字符表示,这个namedtuple有三个元素,分别名为name,age和gender。

             通过Bob=Person(name=’Bob’,age=30,gender=’male’)这种方式,这类似于Python中类对象 的使用

    import collections
     
    Person=collections.namedtuple('Person','name age gender')
    Bob=Person(name='Bob',age=30,gender='male')
    
    print( 'Representation:',Bob)
    #Representation: Person(name='Bob', age=30, gender='male')
    
    #打印属性
    Jane=Person(name='Jane',age=29,gender='female')
    print( 'Field by Name:',Jane.name)
    #Field by Name: Jane
    
    #格式化打印
    print ("%s is %d years old %s" % Jane)
    #Jane is 29 years old female
  • 相关阅读:
    Go-结构体
    Go-指针
    Go-函数
    pycharm激活码
    python Ajax的使用
    python djangjo完整的实现添加的实例
    python 获取表单的三种方式
    python django ORM
    python django 模板语言循环字典
    python djangjo 文件上传
  • 原文地址:https://www.cnblogs.com/onenoteone/p/12441778.html
Copyright © 2011-2022 走看看