python namedtuple

it2022-05-08  20

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('\nRepresentation:%s' % (str(bob))) jane = Person(name='Jane', age=29,gender='female') print('\nField 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语言中结构体童鞋来说,这个可以说是最好的替代品!

转载于:https://www.cnblogs.com/hustxujinkang/p/4643652.html


最新回复(0)