如何执行部分继承 [英] How to perform partial inheritance

查看:166
本文介绍了如何执行部分继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类例如:

class Parent(object):

    def hello(self):
        print 'Hello world'

    def goodbye(self):
        print 'Goodbye world'


class Child(Parent):
    pass

class Child必须只从Parent继承hello()方法并且不应该提到再见()。
有可能吗?

class Child must inherit only hello() method from Parent and and there should be no mention of goodbye(). Is it possible ?

ps是的,我读过 this

重要提示:我只能修改Child类(在父类中)所有可能的都应该保留原样)

Important NOTE: And I can modify only Child class (in the parent class of all possible should be left as is)

推荐答案

解决方案取决于你想要这样做的原因。如果你想避免将来错误地使用该类,我会这样做:

The solution depends on why you want to do it. If you want to be safe from future erroneous use of the class, I'd do:

class Parent(object):
    def hello(self):
        print 'Hello world'
    def goodbye(self):
        print 'Goodbye world'

class Child(Parent):
    def goodbye(self):
        raise NotImplementedError

这是明确的你可以在异常消息中包含解释。

This is explicit and you can include explanation in the exception message.

如果你不想使用父类中的很多方法,那么更好的方式是使用合成而不是继承:

If you don't want to use a lot of methods from the parent class a better style would be to use composition instead of inheritance:

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()

这篇关于如何执行部分继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆