3

I have a base class like the following:

class Base(object):
    def __init__(self, arg1, arg2):
        #Declare self
        self.arg1 = arg1
        self.arg2 = arg2

    @classmethod
    def from_ini_file(cls, f):
        # Get arg1 and arg2 from ini file
        return cls(arg1, arg2)

And then I want to be able to use the classmethod constructor in a derived class. Naively, I tried:

class Derived(Base):
    def __init__(self):
        f = 'default.ini'
        Base.from_ini_file(f)

But this doesn't work. I think I understand why this doesn't work, but I haven't been able to figure out how to do this correctly, if it's possible.

Thanks for any and all help.

Edit

This feels very inelegant but I'm currently going with:

class Derived(Base):
    def __init__(self):
        t = Base.from_ini_file('default.ini')
        Base.__init__(t.arg1, t.arg2)

There's a lot of redundant operations here, and I don't like having to have the arguments of the Base.init function be something that necessarily gets saved to the object for use in this way. So I'm all ears for better solutions. Thanks again.

0

2 Answers 2

1

from_ini_file returns a new instance, so you have to call this method from your derived class also form a classmethod:

class Derived(Base):
    @classmethod
    def from_default_ini(cls):
        f = 'default.ini'
        return cls.from_ini_file(f)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick response! Sorry for being dense, but you're basically telling me that there is no way I can call the classmethod from within the __init__() of the derived class. This is a bit unsatisfying because one of the main points of the derived class is to abstract where the default instantiation information comes from. I.e., I don't want the user to care that the source code is using an ini file to construct the Base object. They're just initiating the derived object using the default construction operation. Does that make sense?
1

I know this is super old and I'm sure you've moved on, but thought I'd share how I implemented something similar

class Base(object):
    def __init__(self, arg1, arg2):
        #Declare self
        self.arg1 = arg1
        self.arg2 = arg2

    @staticmethod
    def from_ini_file(f):
        # Get arg1 and arg2 from ini file
        return Base(arg1, arg2)
myInstance = Base.from_ini_file(f)

If you wanted to completely obscure the ini file:

class Derived(Base):
    def __init__(self, f='default.ini'):
        # Get arg1 and arg2 from ini file
        super().__init__(arg1, arg2)
defaultInstance = Derived()
customInstance = Derived(customF)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.