2016-06-11 73 views
0

我嘗試從int繼承併爲其編寫increase()函數。繼承int並增加python

import math 


class Counter(int): 

    def increase(self): 
     self += 1 
     # it should be less then 2**32 
     maximum = math.pow(2, 32) 
     if self > maximum: 
      self -= maximum 



counter = Counter(10) 
print counter 
counter.increase() 
print counter 
counter.increase() 
print counter 

輸出繼電器:

10 
10 
10 

它不工作!爲什麼以及如何編寫代碼?

+0

看起來像一個奇怪的想法繼承'int'。爲什麼不只是'int'屬性? – erip

+0

每次計算「最大值」也是一個壞主意。 – erip

回答

1

由於整數在Python中是不可變的,因此不可能在這裏執行您想要做的事情。一旦它們被創建,它們就不能被改變。

Python Documentation

某些對象的值可以改變。可以改變值的對象被認爲是可變的;一旦創建它們的值不可更改的對象稱爲不可變的。 ...對象的可變性由其類型決定;例如數字,字符串和元組是不可變的,而字典和列表是可變的。

根據您要使用這個你能做什麼,而不是什麼如下:

class Counter(object): # new style object definition. 

    def __init__(self, num): 
     self.value = num 
     # this is 32bit int max as well, same as pow(2,32) function. 
     self.maximum = 0xFFFFFFFF 
    def increase(self): 
     self.value += 1 

     if self.value > self.maximum: 
      self.value -= self.maximum 

    def __repr__(self): # representation function. 
     return str(self.value) 

    def __str__(self): # string function 
     return str(self.value) 

counter = Counter(10) 
print counter 
counter.increase() 
print counter 
counter.increase() 
print counter