【问题标题】:inheritance from int and increase in python [duplicate]从int继承并在python中增加[重复]
【发布时间】:2016-10-12 09:04:48
【问题描述】:

我尝试从int 继承并为其编写increase() 函数。

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

这行不通!为什么以及如何编写代码?

【问题讨论】:

  • 继承int 似乎是个奇怪的想法。为什么不只是有一个int 属性?
  • 另外,每次都计算 maximum 是个坏主意。

标签: python


【解决方案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

【讨论】:

    猜你喜欢
    • 2011-03-15
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 2021-02-05
    • 2015-05-24
    相关资源
    最近更新 更多