Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize base class with variable not coming from derived class

I'm trying to provide framework which allows people to write their own plugins. These plugins are basically derived classes. My base class needs some variables to initialize, how can I initialize my base class without having to let my derived class feed the variable in the base class initialization?

#!/bin/python

class BaseClass():
    def __init__(self,config):
        self.config=config
    def showConfig(self):
        print "I am using %s" % self.config

class UserPlugin(BaseClass):
    def __init__(self,config):
        BaseClass.__init__(self,config)
    def doSomething(self):
        print "Something"


fubar = UserPlugin('/tmp/config.cfg')
fubar.showConfig()

My goal is to avoid the need to define the config parameter in the UserPlugin class, since this is something I don't want the user who writes a plugin to be bothered with.

like image 839
jay_t Avatar asked Apr 23 '26 15:04

jay_t


2 Answers

You can use argument lists to pass any remaining arguments to the base class:

class UserPlugin(BaseClass):
    def __init__(self, *args, **kwargs):
        BaseClass.__init__(self, *args, **kwargs)
like image 100
phihag Avatar answered Apr 26 '26 04:04

phihag


Based on your Pastebin code, how about this? This avoids using a separate global, instead using a class attribute, which is accessible as a member to all derived classes and their instances.

#!/bin/python

class BaseClass():
    config = '/tmp/config.cfg'
    def __init__(self):
        pass
    def showConfig(self):
        print "I am using %s" % self.config

class UserPlugin(BaseClass):
    def __init__(self):
        BaseClass.__init__(self)
    def doSomething(self):
        print "Something"


fubar = UserPlugin()
fubar.showConfig()

This was the other way to do it that I mentioned before. Keep in mind that if you want to change the value of BaseClass.config itself, you should access it directly (i.e. BaseClass.config = '/foo/path'; otherwise, you wind up creating a custom UPinstance.config value, leaving BaseClass.config unchanged.

like image 28
senderle Avatar answered Apr 26 '26 04:04

senderle



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!