+-
Python中的继承?
假设我有以下 python基类:

class BaseClass(object):
    def a():
        """This method uses method b(), defined in the inheriting class"""

还有一个继承BaseClass的类:

class UsedByUser(BaseClass):
    def b():
        """b() is defined here, yet is used by the base class"""

我的用户只会创建UsedByUser类的实例.典型用途是:

if __name__ == '__main__':
    # initialize the class used by the user        
    usedByUser = UsedByUser()

    # invoke method a()
    usedByUser.a()

我的问题是,上述使用是否有问题?这是一个有效的方法,还是我还必须在BaseClass中定义方法b()然后在UsedByUser中覆盖它?

最佳答案
我也会在BaseClass中定义b方法:

class BaseClass(object):
    def b(self):
        raise NotImplementedError('b must be implemented by a subclass')

请记住:显式优于隐式,并且假设方法a无论如何都需要方法b,更好地引发有意义的异常而不是一般的AttributeError.

值得指出的是,从语法的角度来看,这绝对不是必需的,但它增加了代码的清晰度并强制子类提供实现.

点击查看更多相关文章

转载注明原文:Python中的继承? - 乐贴网