from collections import namedtuple
# create a new data type (internally it defines a class ContactData):
ContactData = namedtuple("ContactData", ["name", "city", "state"])
# create an object as instance of our new data type
alex = ContactData("Alex", "Taiwan", "Vietnam")
# access our new object
print(alex) # output: ContactData(name='Alex', city='Taiwan', state='Vietnam')
print(alex.city) # output: Taiwan
print(alex[1]) # output: Taiwan
alex[0] = "Alexander" # set new value
print(alex.name) # output: Alexander
模块
collections
中的名称元组也有帮助:你可以使用解包。在
在Python3中,使用
^{pr2}$*
运算符可以做更多的事情。在请参考PEP 448 -- Additional Unpacking Generalizations以获得更多的概括。在
您可以创建自定义
namedtuple
数据类型:相关问题 更多 >
编程相关推荐