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)
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()
class Child(Parent):
def __getattribute__(self, attr):
if attr == 'goodbye':
raise AttributeError()
return super(Child, self).__getattribute__(attr)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With