When subclassing a base class, an inherited method is not working as expected.
I’ve broken my module into a couple of pieces (sorry if this difficult to follow) all in a directory named Lan.
in Lan/__init__.py I have:
from Bridge import Bridge
from Ethernet import Ethernet
from BaseInterface import BaseInterface
def IfCtl(iftype):
for cls in BaseInterface.__subclasses__():
if iftype in cls.iftypes():
return cls()
raise ValueError
In Lan/Bridge.py
from Lan.BaseInterface import BaseInterface
class Bridge(BaseInterface):
def __init__(self):
BaseInterface.__init__(self)
@staticmethod
def iftypes():
return ['br', 'bridge']
def up(self):
return 'Bringing up Bridge'
def down(self):
return 'Bringing down Bridge'
and finally in Lan/BaseInterface.py:
from time import sleep
class IfaceNotImplementedError(NotImplementedError):
def __init__(self, methodName):
self.methodName = methodName
def __str__(self):
return "Method %s must be subclassed" % self.methodName
class BaseInterface(object):
@staticmethod
def iftypes(): return ['']
def up(self): raise IfaceNotImplementedError('up()')
def down(self): raise IfaceNotImplementedError('down()')
def restart(self, delay = 1.0):
self.down()
sleep(delay)
self.up()
Everything seems to work as expected except the restart() method inherited from BaseInterface. The method appears to run because there is a pause when I run it, but I returns no data. I’d expect to see the text returned by the overwritten up() and down() methods.
>>> from Lan import IfCtl
>>> InterFace = IfCtl('br')
>>> print InterFace.down()
Bringing down Bridge
>>> print InterFace.up()
Bringing up Bridge
>>> print InterFace.restart()
None
>>>
What am I doing wrong?
Your
restart()method does not return anything. If you want it to carry the return value of up you need the last line to readreturn self.up(). Otherwise, it will always returnNonelike it is now – the default return for any function that does not have an explicit return value.