[
146
]
We'll answer these questions as we go, but let's start with the simplest possible
Document
class first and see what it can do:
class Document:
def __init__(self):
self.characters = []
self.cursor = 0
self.filename = ''
def insert(self, character):
self.characters.insert(self.cursor, character)
self.cursor += 1
def delete(self):
del self.characters[self.cursor]
def save(self):
with open(self.filename, 'w') as f:
f.write(''.join(self.characters))
def forward(self):
self.cursor += 1
def back(self):
self.cursor -= 1
This simple class allows us full control over editing a basic document. Have a look
at it in action:
>>> doc = Document()
>>> doc.filename = "test_document"
>>> doc.insert('h')
>>> doc.insert('e')
>>> doc.insert('l')
>>> doc.insert('l')
>>> doc.insert('o')
>>> "".join(doc.characters)
'hello'
>>> doc.back()
>>> doc.delete()
>>> doc.insert('p')
>>> "".join(doc.characters)
'hellp'
www.it-ebooks.info
Chapter 5
[
147
]
Looks like it's working. We could connect a keyboard's letter and arrow keys to these
methods and the document would track everything just fine.
But what if we want to connect more than just arrow keys. What if we want to connect
the
Home
and
End
keys as well? We could add more methods to the
Document
class
that search forward or backwards for newline characters (in Python, a newline
character, or
\n
represents the end of one line and the beginning of a new one) in
the string and jump to them, but if we did that for every possible movement action
(move by words, move by sentences,
Page Up
,
Page Down
, end of line, beginning of
whitespace, and more), the class would be huge. Maybe it would be better to put those
methods on a separate object. So, let us turn the cursor attribute into an object that is
aware of its position and can manipulate that position. We can move the forward and
back methods to that class, and add a couple more for the
Home
and
End
keys:
class Cursor:
def __init__(self, document):
self.document = document
self.position = 0
def forward(self):
self.position += 1
def back(self):
self.position -= 1
def home(self):
while self.document.characters[
self.position-1] != '\n':
self.position -= 1
if self.position == 0:
# Got to beginning of file before newline
break
def end(self):
while self.position < len(self.document.characters
) and self.document.characters[
self.position] != '\n':
self.position += 1
This class takes the document as an initialization parameter so the methods have
access to the content of the document's character list. It then provides simple
methods for moving backwards and forwards, as before, and for moving to the
home
and
end
positions.
www.it-ebooks.info
When to Use Object-oriented Programming
Do'stlaringiz bilan baham: |