2017-02-19 120 views
3

我只是想通过参考官方的Python文档https://docs.python.org/3.4/library/enum.html,特别是8.13.13.2和8.13.13.4的示例来制作一个Python 3中的Enum。Python 3枚举:枚举继承另一个枚举不起作用?

我的目标是有一个枚举,我可以迭代,比较,也有三个独立的属性。不过,我不断发现此错误:

AttributeError: can't set attribute 

似乎在__init__()构造一个错误。

代码:

我这样一个唯一的类首先尝试:

class Hand(Enum): 
    FIVE_OF_KIND = (6,'FIVE_OF_KIND',[5]) 
    FOUR_OF_KIND = (5,'FOUR_OF_KIND',[4,1]) 
    FULL_HOUSE = (4,'FULL_HOUSE',[3,2]) 
    THREE_OF_KIND = (3,'THREE_OF_KIND',[3,1,1]) 
    DOUBLE_PAIR = (2,'DOUBLE_PAIR',[2,2,1]) 
    PAIR = (1,'PAIR',[2,1,1,1]) 
    NOTHING = (0,'NOTHING',[1,1,1,1,1]) 

    def __init__(self, val, name, struct): 
     self.val = val 
     self.name = name 
     self.struct = struct 

    def __ge__(self, other): 
     if self.__class__ is other.__class__: 
      return self.value >= other.value 
     return NotImplemented 

    def __gt__(self, other): 
     if self.__class__ is other.__class__: 
      return self.value > other.value 
     return NotImplemented 

    def __le__(self, other): 
     if self.__class__ is other.__class__: 
      return self.value <= other.value 
     return NotImplemented 

    def __lt__(self, other): 
     if self.__class__ is other.__class__: 
      return self.value < other.value 
     return NotImplemented 
有两类

,其次是这样的:

class OrderedEnum(Enum): 
    def __ge__(self, other): 
     if self.__class__ is other.__class__: 
      return self.value >= other.value 
     return NotImplemented 

    def __gt__(self, other): 
     if self.__class__ is other.__class__: 
      return self.value > other.value 
     return NotImplemented 

    def __le__(self, other): 
     if self.__class__ is other.__class__: 
      return self.value <= other.value 
     return NotImplemented 

    def __lt__(self, other): 
     if self.__class__ is other.__class__: 
      return self.value < other.value 
     return NotImplemented 


class Hand(OrderedEnum): 
    FIVE_OF_KIND = (6,'FIVE_OF_KIND',[5]) 
    FOUR_OF_KIND = (5,'FOUR_OF_KIND',[4,1]) 
    FULL_HOUSE = (4,'FULL_HOUSE',[3,2]) 
    THREE_OF_KIND = (3,'THREE_OF_KIND',[3,1,1]) 
    DOUBLE_PAIR = (2,'DOUBLE_PAIR',[2,2,1]) 
    PAIR = (1,'PAIR',[2,1,1,1]) 
    NOTHING = (0,'NOTHING',[1,1,1,1,1]) 

    def __init__(self, val, name, struct): 
     self.val = val 
     self.name = name 
     self.struct = struct 

回答

2

Enum对象已经有一个name属性(例如,见第8.13.13.3节),显然你不能设置它 - 哪一个是当你想到一个枚举应该如何表现的时候。你可以达到你想要的效果:

from enum import Enum 

class OrderedEnum(Enum): 
    # Same as your code. 

class Hand(OrderedEnum): 

    FIVE_OF_KIND = (6, [5]) 
    FOUR_OF_KIND = (5, [4,1]) 
    FULL_HOUSE = (4, [3,2]) 
    THREE_OF_KIND = (3, [3,1,1]) 
    DOUBLE_PAIR = (2, [2,2,1]) 
    PAIR   = (1, [2,1,1,1]) 
    NOTHING  = (0, [1,1,1,1,1]) 

    def __init__(self, val, struct): 
     # No need to set self.name. It's already handled. 
     self.val = val 
     self.struct = struct 

for h in Hand: 
    print((h.name, h.val, h.struct)) 
+0

谢谢!无法假定该属性已经存在! – madtyn