继承int的类中的按位运算 [英] Bitwise operations in class inheriting int

查看:127
本文介绍了继承int的类中的按位运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承自int,因为我想为按位操作实现一个简单的接口。由于int的非可变性,我必须使用整数成员函数,如 int .__和__ ,...。

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)))

在我的一个成员函数中,我想使用 | = & = 函数,但整数没有 __ ior __ __ iand __ 成员函数。所以我的问题是如何解决这个问题?。

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?.

我不想简化二进制操作,我想操纵整数的位。例如

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

仍应有效。

推荐答案

int s不是可订阅的,也不是不可变的,所以你不能编写一个有效的 __ setindex __()方法。似乎描述基本上是一个可变的位向量类,例如这一个似乎是由Guido写的。您可以使用提供的 __ int __() __ long __()方法将其转换为整数值(尽管我不知道相信你不再需要后者了。

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).

这篇关于继承int的类中的按位运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆