Login and get coding
When we want to transform our data often, method chaining is a wonderful paradigm that allows us to write elegant and less error-prone code.
For example, given a string
s, we can do the following in Python
When working with databases, we often have code snippets like the next one:session.query(Engineer).\
filter(Engineer.id == Employee.id).\
filter(Employee.name == 'dilbert').\
Implementing method chaining is not hard, although there are at least two different ways of achieving this functionality.
Now it's your turn to try it out.
In this Bite you are asked to implement a simple document class that can be used to create text documents.
For this Bite, a document is a list of strings, each string representing exactly one line.
The order in the list is the order of the document. Indices start at 0.
However, because working with documents basically means a lot of repeated function calls, you want to provide at least some convenience by offering method chaining.
Be aware that there are (at least) two ways to achieve method chaining and you can choose which one you want to implement here. Both will pass the tests.
With method chaining it is easy to execute multiple transformations of a document at once:d = (
.add_line("My first sentence.")
.add_line("My second sentence.")
>>> My first sentence. My second sentence
>>> ['first', 'introduction', 'my', 'second', 'sentence']
We provided you with a skeleton of a
Documentclass that offers typical methods for manipulating documents.
For this bite, we only consider methods that change whole lines, which makes things a lot easier.
Feel free to add more methods to your liking.
If you wonder why there is no method for undoing the last action, stay tuned for another Bite!
30 out of 33 users completed this Bite.
Will you be Pythonista #31 to crack this Bite?
Resolution time: ~93 min. (avg. submissions of 5-240 min.)
Pythonistas rate this Bite 7.0 on a 1-10 difficulty scale.
» Up for a challenge? 💪