若一个类的存在只是为了记录某种数据结构,那么有两种方法
1. 利用slots方法
定义了slots以后,用户只能使用slots中定义的属性
class Date:
__slots__ = ['year', 'month', 'day']
def __int__(self, year, month, day):
self.year = year
self.month = month
self.day = day
2. 利用命名元组,namedtuple
from collections import namedtuple
if __name__ == '__main__':
Date = namedtuple('Date', ['year', 'month', 'day'])
date = Date('2017', '04', '17')
print(date.year, date.month, date.day)
# 修改某个属性的值
date = date._replace(year=2016)