从子类中的Enum返回值

时间:2019-05-09 08:23:32

标签: python-3.x

我想从子类中的Enum返回字符串值。我有这样的课程结构

Class1           
  |              
  |--subclass       
  |      |            
  |      |----Enum         

现在我想从枚举中返回一个字符串值。

我知道如何返回值return str(self.value)

def __str__(self):
        return str(self.value)
class GSSML:
    class ProsodyAttributes:
        class Rate(Enum):
            def __srt__(self):
                return self.value
            x_slow = 'x-slow'
            slow = 'slow'
            medium = 'medium'
            fast = 'fast'
            x_fast = 'x-fast'
            default = 'default'

我的测试代码

import gssml

def main():
    ssml = gssml.GSSML()
    print(ssml.ProsodyAttributes.Rate.x_fast)


if __name__ == '__main__':
    main()

现在,我希望它返回x-fast 但是我得到了Rate.x_fast

我不知道我在做什么错。请帮助

1 个答案:

答案 0 :(得分:0)

您的代码未返回正确的值,因为您将dunder方法__str__误译为__srt__


In [15]: from enum import Enum 
    ...:  
    ...: class GSSML: 
    ...:     class ProsodyAttributes: 
    ...:         class Rate(Enum): 
    ...:             def __str__(self): 
    ...:                 return self.value 
    ...:             x_slow = 'x-slow' 
    ...:             slow = 'slow' 
    ...:             medium = 'medium' 
    ...:             fast = 'fast' 
    ...:             x_fast = 'x-fast' 
    ...:             default = 'default' 
    ...:  
    ...: ssml = GSSML() 
    ...: print(ssml.ProsodyAttributes.Rate.x_fast)                                                                                                                                
x-fast