Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading