Search code examples
pythonstatic-constructor

How to extend a static base constructor?


I'm using the Python bitmap package.

It does almost everything I need, but it don't work with hexadecimal values, which are needed by my application, so I extended it like this:

import bitmap
class BitMap(bitmap.BitMap):
    def tohexstring(self):
        val = self.tostring()
        st = "{0:0x}".format(int(val,2))
        return st.zfill(self.sz/4)

The base class has a static constructor from string:

bitmap.BitMap.fromstring("01010101")

I can make one from hexadecimal converting the hex value to bin:

bitmap.BitMap.fromstring(format(int("aa",16),"08b"))

But the returned class is the original bitmap class and not the extended one.

How can I use this constructor but still return my extended class?


Solution

  • bitmap.BitMap.fromstring is a class method, not a static method, but has been implemented incorrectly by the author. The line:

    bm = BitMap(nbits)
    

    should really be

    bm = cls(nbits)
    

    in which case you could call fromstring on your subclass and get an instance of the subclass. You could fork the repo, implement this and make a pull request to have this included in the package (or just use your fork in your package). You could also raise an issue on their repo to see how they'd prefer you to proceed.

    Alternatively, implement fromstring correctly in your own subclass and shadow the broken base class implementation.