Overview
I have a python class inheritance structure in which most methods are defined in the base class and most attributes on which those methods rely are defined in child classes.
The base class looks roughly like this:
class Base(object):
__metaclass__ = ABCMeta
@abstractproperty
def property1(self):
pass
@abstractproperty
def property2(self):
pass
def method1(self):
print(self.property1)
def method2(self, val):
return self.property2(val)
while the child class looks like this:
class Child(Base):
property1 = 'text'
property2 = function
where function
is a function that looks like this:
def function(val):
return val + 1
Obviously the code above is missing details, but the structure mirrors that of my real code.
The Problem
When I attempt to use method1
in the base class everything works as expected:
>>> child = Child()
>>> child.method1()
'text'
However, attempting the same for method2
spits an error:
>>> child = Child()
>>> child.method2(1) # expected 2
TypeError: method2() takes exactly 1 argument (2 given)
The second passed argument is the Child
class itself.
I'm wondering if there's a way to avoid passing this second Child
parameter when calling method2
.
Attempts
One workaround I've found is to define an abstract method in the base class then build that function in the child classes like so:
class Base(object):
__metaclass__ = ABCMeta
@abstractproperty
def property1(self):
pass
@abstractmethod
def method2(self, val):
pass
def method1(self):
print(self.property1)
class Child(Base):
property1 = 'text'
def method2(self, val):
return function(val)
However, I would prefer that this method live in the base class. Any thoughts? Thanks in advance!