4

例如,我有两个课程:

class Parent(object):

    def hello(self):
        print 'Hello world'

    def goodbye(self):
        print 'Goodbye world'


class Child(Parent):
    pass

类 Child 必须仅从 Parent 继承 hello() 方法,并且不应提及 goodbye()。可能吗 ?

ps 是的,我读过这个

重要说明:我只能修改子类(在所有可能的父类中都应该保持原样)

4

3 回答 3

15

解决方案取决于您为什么要这样做。如果您想避免将来错误使用该课程,我会这样做:

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()
于 2012-06-26T09:50:59.353 回答
3
class Child(Parent):
    def __getattribute__(self, attr):
        if attr == 'goodbye':
            raise AttributeError()
        return super(Child, self).__getattribute__(attr)
于 2012-06-26T09:49:32.013 回答
0

这个 Python 示例展示了如何设计类来实现子类继承:

class HelloParent(object):

    def hello(self):
        print 'Hello world'

class Parent(HelloParent):
    def goodbye(self):
        print 'Goodbye world'


class Child(HelloParent):
    pass
于 2012-06-26T09:30:30.457 回答