python – 如何执行部分继承
发布时间:2020-12-20 12:20:24 所属栏目:Python 来源:网络整理
导读:我有两个类,例如: class Parent(object): def hello(self): print 'Hello world' def goodbye(self): print 'Goodbye world'class Child(Parent): pass class Child必须只从Parent继承hello()方法,并且不应该提及goodbye(). 可能吗 ? ps是的,我读了this 重
我有两个类,例如:
class Parent(object): def hello(self): print 'Hello world' def goodbye(self): print 'Goodbye world' class Child(Parent): pass class Child必须只从Parent继承hello()方法,并且不应该提及goodbye(). ps是的,我读了this 重要说明:我只能修改Child类(在所有可能的父类中应保留原样) 解决方法
解决方案取决于您为什么要这样做.如果你想避免将来错误地使用课程,我会这样做:
class Parent(object): def hello(self): print 'Hello world' def goodbye(self): print 'Goodbye world' class Child(Parent): def goodbye(self): raise NotImplementedError 这是明确的,您可以在异常消息中包含说明. 如果您不想使用父类中的许多方法,那么更好的方式是使用组合而不是继承: class Parent(object): def hello(self): print 'Hello world' def goodbye(self): print 'Goodbye world' class Child: def __init__(self): self.buddy = Parent() def hello(self): return self.buddy.hello() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |