码迷,mamicode.com
首页 > 编程语言 > 详细

Python中collections模块的namedtuple的使用

时间:2021-02-16 12:02:48      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:ring   模块   tuples   mile   生成   error   ike   work   cti   

使用namedtuple方法可以代替手动生成一个类

# Why Python is Great: Namedtuples
# Using namedtuple is way shorter than
# defining a class manually:
>>> from collections import namedtuple
>>> Car = namedtuple(‘Car‘, ‘color mileage‘)

# Our new "Car" class works as expected:
>>> my_car = Car(‘red‘, 3812.4)
>>> my_car.color
‘red‘
>>> my_car.mileage
3812.4

# We get a nice string repr for free:
>>> my_car
Car(color=‘red‘ , mileage=3812.4)

# Like tuples, namedtuples are immutable:
>>> my_car.color = ‘blue‘
AttributeError: "can‘t set attribute"

Python中collections模块的namedtuple的使用

标签:ring   模块   tuples   mile   生成   error   ike   work   cti   

原文地址:https://www.cnblogs.com/jiaoran/p/14398814.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!