Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instantiating a derived class object with a base class classmethod in python

Tags:

python

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.

like image 434
K. Westfall Avatar asked Sep 27 '26 03:09

K. Westfall


2 Answers

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)
like image 168
Daniel Avatar answered Sep 28 '26 17:09

Daniel


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)
like image 23
Schalton Avatar answered Sep 28 '26 17:09

Schalton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!