I want my class to inherit the BitArray
class but I'm running into a problem in the constructors. I have several positional and keyword arguments I want to use in the child but the first positional argument is always used in the parent for some reason. Does anybody know why this is and how to fix it?
Example Code:
from bitstring import BitArray
class MyClass(BitArray):
def __init__(self, var1, kwvar1=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.var1=var1
self.kwvar1=kwvar1
a = MyClass('0xff', kwvar1="myvar")
print(a.b) # this should be empty
print(a.var1)
print(a.kwvar1)
Output:
11111111
0xff
myvar
The output of a.b
should be empty since I didn't pass any extra arguments that would have been passed to super().__init__()
, but instead it is a BitArray of ones. Furthermore, if I do give MyClass
extra arguments, then I get a key error. For instance, if I change the code above to :
a = MyClass('0xff','0x0f0f', kwvar1="myvar")
then I get a KeyError
:
C:\Python\Python311\Lib\site-packages\bitstring.py", line 964, in __new__
return _cache[auto]
~~~~~~^^^^^^
KeyError: '0xff'
It seems to me that in this example a.b
should return 00110011
since '0x0f0f'
would normally be the first argument passed to super().__init__()
right? What am I missing here?
CodePudding user response:
It's because the BitArray defines the __new__()
. See the implementation.
So, do like this.
from bitstring import BitArray
class MyClass(BitArray):
def __init__(self, var1, *args, kwvar1=None, **kwargs):
super().__init__(*args, **kwargs)
self.var1=var1
self.kwvar1=kwvar1
def __new__(cls, var1, *args, kwvar1=None, **kwargs):
return super().__new__(cls, *args, **kwargs)
And don't forget to reorder kwvar1
and args
arguments.