2017-02-19 119 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