开发者

Inherited method returning no data

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开发者_如何学JAVA 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?


You are not returning from restart

You either need to change:

def up(self):
    return 'Bringing up Bridge'

to

def up(self):
    print 'Bringing up Bridge'

or change:

def restart(self, delay = 1.0):
    self.down()
    sleep(delay)
    self.up()

to

def restart(self, delay = 1.0):
    vals = []
    vals.append(self.down())
    sleep(delay)
    vals.append(self.up())
    return vals


Your restart() method does not return anything. If you want it to carry the return value of up you need the last line to read return self.up(). Otherwise, it will always return None like it is now - the default return for any function that does not have an explicit return value.


change:

def restart(self, delay = 1.0):
    self.down()
    sleep(delay)
    self.up()

to:

def restart(self, delay = 1.0):
    print self.down()
    sleep(delay)
    print self.up()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜