Function into Class
Convert 3 functions into a class with 3 methods.
Before
def calculate_area(length, width):
result = length * width
return result
def calculate_perimiter(length, width):
result = 2 * (length + width)
return result
def calculate_volume(length, width, height):
result = length * width * height
return result
After
class Calculator:
@staticmethod
def get_area(len, wid):
return len * wid
@staticmethod
def get_perimiter(len, wid):
return 2 * (len + wid)
@staticmethod
def get_volume(len, wid, hei):
return len * wid * hei
Preview
Command
%scalculate<enter>cget<esc>
O@staticmethod
<esc>jxxs\w+<enter>s
length|width|height<enter>
bllled%sresult =<enter>C
<alt-(>;ddss<enter>
xd%>O<backspace>
class Calculator:
-
%
selects the entire file -
s
searches inside the current selection and creates sub-selections based on a pattern. Inputcalculate
then hit<enter>
to make a selection on all instances of the word -
c
then typeget
to change each "calculate" word into a "get" -
<esc>
to go back to normal mode -
Use
O
to create an empty line above each cursor, write:@staticmethod
-
Hit
<esc>
to go into normal mode. -
We need to select 2 lines below the current line, first go down with
j
and then pressxx
which will select the current line, and then select the next line In total we now have 3 cursors each with 2 lines selected, which includes the first line of the bodies of each function and the function definition themselves -
s
brings up a prompt to select sub-selections by a given regex. The\w+
regex selects each word, type it and then<enter>
-
s
again then typelength|width|height
followed by<enter>
. This will look at the contents of the current selections, and create sub-selections where it finds the regex which means "length or width or height". So we select each instance of those 3 words -
Our cursor is currently at the end of each word. Let's go to the beginning with
b
-
We want to keep the first 3 characters and discard the rest from each of the parameters. To do this, move to the 4th character with
lll
-
Use
e
to select until the end of each word and thend
to delete it -
Select the entire file again with
%
followed bys
to bring up selection prompt again -
Write
result =
followed by<enter>
to select all instances of that string -
C
creates a new selection on the line directly below, for each cursor -
Use
<alt-(>
to rotate the contents of the selection backward -
;
collapses each cursor into a single selection -
dd
deletes two characters on each of the 6 lines -
s
to bring up the prompt, then inputs
followed by<enter>
to select all "s" characters -
Select each of the lines with
x
followed byd
to delete -
Select whole file with
%
and indent with>
-
O
creates a newline above and enters Insert mode, then<backspace>
to delete an extra tab -
Write this:
class Calculator: