在Python中重写int子类中的int值是不可能的?

时间:2018-04-21 17:38:48

标签: python python-3.x int subclass

我目前正处于一个python 3项目中,我通过二进制表示整数工作,因此,我做了一个让我自己更容易工作的方法,但我不能让它完全发挥作用:< / p>

class EnhancedInt(int):
    def __init__(self, x: Union[str, bytes, SupportsInt] = ...) -> None:
        int.__init__(int(x))

    def __getitem__(self, key: int) -> int:
        """Returns the digit number key from the binary representation of self  (little endian)

        Args:
            key (int):

        Returns:
            int:
        """
        if key > 32:
            raise ValueError("int are 32 bits long, %d given is too much" % key)
        if key < 0:
            raise ValueError("Negative keys not supported, %d given is too low" % key)
        else:
            return EnhancedInt((self >> key) & 1)

    def __setitem__(self, key: int, value: int) -> None:
        if value != 0 and value != 1:
            raise ValueError('Value must be 0 or 1')
        self -= self[key]*pow(2, key)
        if value:
            self += pow(2, key)

所以,那部分不起作用:__setitem__。我理解为什么,更改self似乎有点残酷,但我无法找到值存储在int中的位置。

为了进一步理解,这里是调用我的类的代码:

>>> i = EnhancedInt(5)
>>> print(i[1])
0
>>> i[1] = 1
>>> print(i)
5 ????

我想要返回7,但是现在只返回5个。

1 个答案:

答案 0 :(得分:0)

与我想做的相比,尽管找到了很多工作,但我还是找到了一个可行的解决方案。我做了以下事情:

class EnhancedInt(int):
"""
Does everything a int can do, but can also be addressed bitwise (you can read, write, 
add and delete a bit at given position)
Bit representation is in little endian : the lowest indexes corresponding to the least 
significant bits
"""
def __init__(self, x: Union[str, bytes, SupportsInt]) -> None:
    int.__init__(int(x))
    self.__value__ = int(x)

def __getitem__(self, key: int) -> int:
    """Returns the digit number *key* from the binary representation of *self* (little endian)
    Args:
        key (int): bit number to be returned
    Returns:
        int: value of the bit addressed
    """
    EnhancedInt._check_key_value(key)
    return (self.__value__ >> key) & 1

def __setitem__(self, key: int, value: int) -> None:
    """Changes the value of the *key*th bit of *self* (little endian)
    Args:
        key (int): index of bit to be modified
        value (int): bit value (must be 0 or 1)
    """
    EnhancedInt._check_key_value(key)
    if value != 0 and value != 1:
        raise ValueError("Value must be 0 or 1, %d given" % value)
    if (not self[key]) and value:
        self.__value__ += 1 << key
        return None
    if self[key] and not value:
        self.__value__ -= 1 << key

我还重新定义了用于int类的所有方法。 该方法似乎过大,并且存在其他缺陷。我想找到一种更优雅的方法,但是与此同时。 完整的代码可以在以下地址找到:https://github.com/assombrance/Quantomatic/blob/master/src/data.py