Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform partial inheritance

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)

like image 397
Denis Avatar asked Dec 01 '22 22:12

Denis


2 Answers

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()
like image 93
Michał Kwiatkowski Avatar answered Dec 14 '22 17:12

Michał Kwiatkowski


class Child(Parent):
    def __getattribute__(self, attr):
        if attr == 'goodbye':
            raise AttributeError()
        return super(Child, self).__getattribute__(attr)
like image 39
Aleksei astynax Pirogov Avatar answered Dec 14 '22 18:12

Aleksei astynax Pirogov