Search code examples
pythonclass-method

__init__ in overridden classmethod


I have a small class hierarchy with similar methods and __init__(), but slightly different static (class) read() methods. Specifically will the child class need to prepare the file name a bit before reading (but the reading itself is the same):

class Foo:
    def __init__(self, pars):
        self.pars = pars

    @classmethod
    def read(cls, fname):
        pars = some_method_to_read_the_file(fname)
        return cls(pars)


class Bar(Foo):
    @classmethod
    def read(cls, fname):
        fname0 = somehow_prepare_filename(fname)
        return cls.__base__.read(fname0)        

The problem here is that Bar.read(…) returns a Foo object, not a Bar object. How can I change the code so that an object of the correct class is returned?


Solution

  • cls.__base__.read binds the read method explicitly to the base class. You should use super().read instead to bind the read method of the parent class to the current class.

    Change:

    return cls.__base__.read(fname0)
    

    to:

    return super().read(fname0)