alex_bn_lee

导航

【382】利用 namedtuple 实现函数添加属性

namedtuple 能够实现类似类的效果,tuple 的元素可以通过属性的形式返回,如下所示:

from collections import namedtuple
Student = namedtuple('stu', ['Name', 'Age', 'Height', 'Weight'])
Alex = Student('Alex', 23, '173', '63')
Vincent = Student('Vincent', 20, '172', '57')

Alex.Name
Alex.Age
Alex.Height
Alex.Weight

Vincent.Name
Vincent.Age
Vincent.Height
Vincent.Weight

output:
'Alex'
23
'173'
'63'

'Vincent'
20
'172'
'57'

因此若是想要让函数返回属性的效果,只需让函数的返回值是 namedtuple 即可,如下所示

from collections import namedtuple
def get_info(Name, Age, Height, Weight):
    Student = namedtuple('stu', ['Name', 'Age', 'Height', 'Weight'])
    return Student(Name, Age, Height, Weight)

Alex = get_info('Alex', 23, '173', '63')
Alex.Name
Alex.Age
Alex.Height
Alex.Weight

output:
'Alex'
23
'173'
'63'

 

posted on 2019-03-21 12:24  McDelfino  阅读(281)  评论(0编辑  收藏  举报