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>jj
vglyx<alt-d>xbRkxx
slength|width|height<enter>
bllled%>O<backspace>
class Calculator:
-
%selects the entire file -
ssearches inside the current selection and creates sub-selections based on a pattern. Inputcalculatethen hit<enter>to make a selection on all instances of the word -
cthen typegetto change each "calculate" word into a "get" -
<esc>to go back to normal mode -
Use
Oto create an empty line above each cursor, write:@staticmethod -
Hit
<esc>to go into normal mode. -
jjmoves each cursor down two lines -
vglselects the rest of each line past each cursor -
ycopies each selection -
x<alt-d>selects each cursor's line and deletes the line without copying the selection -
xbselects the last word of each cursor's line -
Rreplaces each selection with the copied selections from earlier -
kxxmoves each cursor up one line and selects that line as well as the line below -
sbrings up a prompt to select sub-selections by a given regex. Typinglength|width|heightfollowed by<enter>will select each instance of those 3 words: length, width, and height -
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
eto select until the end of each word and thendto delete it -
Select whole file with
%and indent with> -
Ocreates a newline above and enters Insert mode, then<backspace>to delete an extra tab -
Write this:
class Calculator: