Den*_*nis 3 python inheritance
我有两个类,例如:
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
pass
Run Code Online (Sandbox Code Playgroud)
class Child必须只从Parent继承hello()方法,并且不应该提及goodbye().可能吗 ?
ps是的,我读过这个
重要说明:我只能修改Child类(在所有可能的父类中应保留原样)
Mic*_*ski 13
解决方案取决于您为什么要这样做.如果你想避免将来错误地使用课程,我会这样做:
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
def goodbye(self):
raise NotImplementedError
Run Code Online (Sandbox Code Playgroud)
这是明确的,您可以在异常消息中包含说明.
如果您不想使用父类中的许多方法,那么更好的方式是使用组合而不是继承:
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()
Run Code Online (Sandbox Code Playgroud)