Bitwise operations in class inheriting int

旧巷老猫 提交于 2019-12-04 04:40:52

问题


I've inherited from int, because I wanted to implement a simple interface for bitwise operations. Due to the non mutability of int, I have to use the integer member functions like int.__and__, ... .

class Bitset(int)
    ...
    def __setitem__(self, index, value):
        if value:
            self.__ior__(1 << int(index))
        else:
            self.__iand__(~(1 << int(index)))

In one of my memberfunctions I want to use the |= and &= functions, but the integer has no __ior__ and __iand__ member functions. So my question is how can I solve this problem?.

Edit:

I dont want to simplify binary operations, I'd like to manipulate the bits of an integer. E.g.

a = Bitset(0)
a[0]
>>>0
a[0] = 1
a[0]
>>>1

But I didn't wan't to reimplement every integer operation, which should still work as well. If I wrap an internal integer I've got to do that. E.g

a = Bitset(0)
a += 1

should still work.


回答1:


ints aren't subscriptable as well as being immutable, so you can't write a working __setindex__() method. It seems like what describing is basically a mutable bit-vector class, such as this one which appears to have been written by Guido. You can use the provided __int__() and __long__() methods to convert it an integer value (although I don't believe you need the latter any more).




回答2:


There is already simple interfaces for bitwise operations (see http://docs.python.org/reference/expressions.html#summary) e.g :

4 >> 1
# 2

You don't have __ior__ and __iand__ but you do have __and__ and __or__. But I suspect that what you want is actually __ror__ and __rand__ which implement bitwise operations. Integers do have those last magic methods. On magic methods see : http://www.rafekettler.com/magicmethods.html#numeric

See also : http://wiki.python.org/moin/BitwiseOperators



来源:https://stackoverflow.com/questions/11825380/bitwise-operations-in-class-inheriting-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!