简体   繁体   English

为什么在继承 `bitstring.BitArray` 时,子构造函数的第一个参数被用于父构造函数?

[英]Why is the first argument of child's constructor being used in parent's constructer when inheriting `bitstring.BitArray`?

I want my class to inherit the BitArray class but I'm running into a problem in the constructors.我希望我的 class 继承BitArray class 但我在构造函数中遇到了问题。 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.我有几个位置和关键字 arguments 我想在孩子中使用,但由于某种原因,第一个位置参数总是在父母中使用。 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: Output:

11111111
0xff
myvar

The output of ab 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. ab的 output 应该是空的,因为我没有将任何额外的 arguments 传递给super().__init__() ,而是它是一个 BitArray。 Furthermore, if I do give MyClass extra arguments, then I get a key error.此外,如果我确实MyClass额外的 arguments,那么我会得到一个关键错误。 For instance, if I change the code above to:例如,如果我将上面的代码更改为:

a = MyClass('0xff','0x0f0f', kwvar1="myvar")

then I get a KeyError :然后我得到一个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 ab should return 00110011 since '0x0f0f' would normally be the first argument passed to super().__init__() right?在我看来,在这个例子中ab应该返回00110011 ,因为'0x0f0f'通常是传递给super().__init__()的第一个参数,对吗? What am I missing here?我在这里错过了什么?

It's because the BitArray defines the __new__() .这是因为 BitArray 定义了__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.并且不要忘记重新排序kwvar1args arguments。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM