5

I have two classes for example:

class Parent(object):

    def hello(self):
        print 'Hello world'

    def goodbye(self):
        print 'Goodbye world'


class Child(Parent):
    pass

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

ps yes, I read this

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

Community
  • 1
  • 1
Denis
  • 7,127
  • 8
  • 37
  • 58
  • Could you elaborate on what is unsatisfactory with the answer given there? – shu zOMG chen Jun 26 '12 at 09:12
  • 3
    possible duplicate of [Is it possible to do partial inheritance with Python?](http://stackoverflow.com/questions/5647118/is-it-possible-to-do-partial-inheritance-with-python) – Ignacio Vazquez-Abrams Jun 26 '12 at 09:14
  • 2
    It's technically possible (with a few dirty hacks), but it's a sure design smell. What's your real use case ? – bruno desthuilliers Jun 26 '12 at 09:17
  • @IgnacioVazquez-Abrams See postscript um – Denis Jun 26 '12 at 09:18
  • @brunodesthuilliers How I can do that ? – Denis Jun 26 '12 at 09:21
  • adding to bruno: check out [How to inherit only a small part of methods from a large class?](https://www.sololearn.com/Discuss/1314620/how-to-inherit-only-a-small-part-of-methods-from-a-large-class-a-into-a-new-class-b-without). Best answer indicates: your class design is messed up, if you want to do that. – PythoNic Aug 12 '22 at 12:31

3 Answers3

18

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()
Michał Kwiatkowski
  • 9,196
  • 2
  • 25
  • 20
3
class Child(Parent):
    def __getattribute__(self, attr):
        if attr == 'goodbye':
            raise AttributeError()
        return super(Child, self).__getattribute__(attr)
1

This Python example shows how to design classes to achieve child class inheritance:

class HelloParent(object):

    def hello(self):
        print 'Hello world'

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


class Child(HelloParent):
    pass
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42