Initialize base class with variable not from derived class
I am trying to provide a framework that allows people to write their own plugins. These plugins are mostly derived classes. My base class needs some variables to initialize, how can I initialize the base class without letting my derived class feed the variable into the base class's 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 having to define a config parameter in the UserPlugin class, as this is something I don't want the user writing the plugin to worry about.
source to share
You can use an argument list to pass the remaining arguments to the base class:
class UserPlugin(BaseClass):
def __init__(self, *args, **kwargs):
BaseClass.__init__(self, *args, **kwargs)
source to share
Based on your Pastebin code, how about this? This avoids using a separate global, instead using a class attribute that is member-accessible 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 another way to do it that I talked about earlier. Keep in mind that if you want to change the value itself BaseClass.config
, you must access it directly (i.e BaseClass.config = '/foo/path'
.; otherwise, you will end up creating the custom value UPinstance.config
, leaving it BaseClass.config
unchanged.
source to share