zoukankan      html  css  js  c++  java
  • 【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'
    
  • 相关阅读:
    python中list的一种取值方式切片
    python之字典(Dictionary)
    表示数字
    自动收售货系统
    明明的随机数
    自守数
    等差数列
    计算字符个数
    字符统计
    Redraimen的走法
  • 原文地址:https://www.cnblogs.com/alex-bn-lee/p/10570864.html
Copyright © 2011-2022 走看看