I have a base class which is inherited from by multiple classes. In the child classes, I want to make a method from the base class uncallable; so I'm using __getattribute__ to raise an error if they are tried from the child class. Dummy example below:
class Base(object):
def f1():
return 1
def f2():
return 2
def f3():
return 3
class Child1(Base):
def __getattribute__(self, name):
if name == 'f1':
raise AttributeError(name)
else:
return super(Child1, self).__getattribute__(name)
class Child2(Base):
def __getattribute__(self, name):
if name == 'f2':
raise AttributeError(name)
else:
return super(Child2, self).__getattribute__(name)
class Child3(Base):
def __getattribute__(self, name):
if name == 'f3':
raise AttributeError(name)
else:
return super(Child3, self).__getattribute__(name)
So in this example, I don't want to be able to call f1 from Child1, f2 from Child2, and f3 from Child3.
Is there a way to re-write this that doesn't have so much code duplication and child classes just inherit the method? This is what I tried, but it first runs into recursion issues because the call to self.blocked_methods in and of itself calls __getattribute__. I imagine there are other issues but can't get past that one.
class Base(object):
blocked_methods = []
def f1():
return 1
def f2():
return 2
def f3():
return 3
def __getattribute__(self, name):
if name in self.blocked_methods:
raise AttributeError(name)
else:
return super(Child3, self).__getattribute__(name)
class Child1(Base):
blocked_methods = ['f1']
class Child2(Base):
blocked_methods = ['f2']
class Child3(Base):
blocked_methods = ['f3']
Baseis not the appropriate base class for any of the three child classes. Consider defining separate mixin classes for each of the three methods instead.