2014年7月23日 星期三

Python - namedtuple

C++中有struct型態可以快速建立一個輕型類別,在該類別中可以含有一些屬性,並用object.attribute的方式存取。在Python則能使用namedtuple做到這件事情。
from collections import namedtuple

## Component definition
Component_t = namedtuple("Component", ["data", "size", "source"])

## Create a component.
def Component(data, size, source):
    return Component_t(data, size, source)

## Convert a list of parameters into a component of module.
#  @param   array is a list.
def toComponent(array):
    return Component_t._make(array)


## Usage
comp1 = Component(data = "hello", size = 5, source = "test.txt")
print(comp1.data)

array = ["world", 5, "test.txt"]
comp2 = toComponent(array)
print(comp2.data)

沒有留言: