【python】命名元组namedtuple的用法

from collections import namedtuple

Student = namedtuple('Student',['id','name','grade'])
student1 = Student(id='1601',name='王宁',grade='9')
student2 = Student('1902','张海',grade='6')
student3 = Student._make(['1803','林彤','7'])

print(student1.id)    #1601
print(student1.name)    #王宁
print(student1.grade)    #9

print(student2[0])    #1902
print(student2[1])    #张海
print(student2[2])    #6

print(student3)    #Student(id='1803',name='林彤',grade='7')

student3 = student3._replace(id='1805')
#_replace方法可以修改对象的属性,与tuple不同,tuple的属性是不可改的。
print(student3)    #Student(id='1805',name='林彤',grade='7')

其中Student = namedtuple('Student',['id','name','grade'])相当于创建了Student类,与以下语句作用相同:

class Student:
    def _init_(self,id,name,grade):
        self.id = id
        self.name = name
        self.grade = grade

个人觉得collections的namedtuple这个方法挺好用的,一行代码就做到了创建类的效果,推荐大家使用。

发布了22 篇原创文章 · 获赞 3 · 访问量 1890

猜你喜欢

转载自blog.csdn.net/weixin_44322399/article/details/103533671