2013-02-22 45 views
0

我要疊加+ - 運營商一個Django場:覆蓋+運營商的Django場

x+y --> x | y (bitwise or) 
x-y --> x & (~y) (almost the inverse of above) 

如果把覆蓋定義是什麼?下面是錯誤的:

class BitCounter(models.BigIntegerField): 
    description = "A counter used for statistical calculations" 
    __metaclass__ = models.SubfieldBase  

    def __radd__(self, other): 
     return self | other 

    def __sub__(self, other): 
     return self & (^other) 

回答

1

首先,創建另一個類從int繼承:

class BitCounter(int): 
    def __add__(self, other): 
     return self | other 

    def __sub__(self, other): 
     return self & (~other) 

然後在該領域的to_python方法返回這個類的一個實例:

class BitCounterField(models.BigIntegerField): 
    description = "A counter used for statistical calculations" 
    __metaclass__ = models.SubfieldBase  

    def to_python(self, value): 
     val = models.BigIntegerField.to_python(self, value) 
     if val is None: 
      return val 
     return BitCounter(val) 
+0

謝謝,工作完美! – MrJ 2013-02-23 00:56:52

1

當你做myobj.myfield,你訪問由field's to_python method,而不是字段本身的返回類型的對象。這是由於Django的一些元類魔法。


您可能想要在此方法返回的類型上覆蓋這些方法。