【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'
标签:namedtuple,Alex,Name,Weight,Age,382,添加,Vincent 来源: https://www.cnblogs.com/alex-bn-lee/p/10570864.html