如何在python中展示旗帜?

时间:2014-04-23 03:18:46

标签: python

与以下C#代码类似:

[Flags]
public enum CandleFlags : short
{
    /// <summary>No flags set</summary>
    None = 0x00,

    /// <summary>IsDoji</summary>
    Doji = 0x01,

    /// <summary>IsHammer</summary>
    Hammer = 0x02,

.....

标志不仅是枚举,因为一个对象可以有多个标志,就像它可以是十字星和锤子一样?

我应该使用int吗?

2 个答案:

答案 0 :(得分:0)

以这种方式:

class CandleFlags:
    is_doji = False
    is_hammer = False

flags = CandleFlags()
flags.is_doji = True

答案 1 :(得分:0)

class CandleFlags:
      DOJI= 0x01
      HAMMER=0x02
      SOMETHING=0x04 

print CandleValue & CandleFlags.DOJI # doji bit is set
print CandleValue & CandleFlags.SOMETHING #something bit is set
print CandleValue & ~CandleFlags.HAMMER # Hammer bit is not set

可能?

你可以用

之类的东西进一步扩展这个概念
class FlagChecker:
    def __init__(self,flags):
       self.flags = flags
    def __getattr__(self,attr):
       if attr.startswith("is"):
          flg = getattr(self.flags,attr[2:].upper(),0)
          return lambda v:bool(v & flg)

checker = FlagChecker(CandleFlags)
print checker.isHammer(candleValue)
print not checker.isDoji(candleValue)
print checker.isYellow(candleValue) #always false ... no YELLOW flag