patternpythonMinor
Console animations
Viewed 0 times
animationsconsolestackoverflow
Problem
I'm a coder who's relatively new to Python and I wanted to spice up my console applications a bit by making animations. The code I've written works perfectly, but I just wanted to know if it was good in a pythonic way and if it follows the OO standards. If not please tell me what could be improved and why.
import subprocess as sp
import time
class Animation(object):
def __init__(self):
self.frames = []
def add_frame(self,frame):
#Adds frame to end of list
self.frames.append(frame)
def remove_last_frame(self):
#Removes last frame in list
del self.frames[-1]
def clear_frames(self):
#Deletes all frames
del self.frames[:]
def get_frames(self):
#Returns list of frames
return self.frames
def run_animation(self,loops,fps):
#Runs the animation at a desired framerate and loops it a given amount of times
delay = 1.0/fps
for x in range(0,loops):
for frame in self.frames:
#The following line clears the shell
tmp = sp.call('clear',shell=True)
print frame
time.sleep(delay)Solution
Reconsider the need for a class
The functions:
Are useless and may be removed.
So you are left with a class that has only
You do not need a class for this:
Please do not make a class for the sake of making a class, often it just complicates the code.
Minor clean-ups:
The functions:
def add_frame(self,frame):
#Adds frame to end of list
self.frames.append(frame)
def remove_last_frame(self):
#Removes last frame in list
del self.frames[-1]
def clear_frames(self):
#Deletes all frames
del self.frames[:]
def get_frames(self):
#Returns list of frames
return self.framesAre useless and may be removed.
So you are left with a class that has only
__init__ and one other method.You do not need a class for this:
def run_animation(frames, loops, fps):
delay = 1.0 / fps
for _ in range(loops):
for frame in frames:
sp.call('clear',shell=True)
print(frame)
time.sleep(delay)Please do not make a class for the sake of making a class, often it just complicates the code.
Minor clean-ups:
x->_as you do not use it.
tmp =-> `as, again, you do not use it.
- print frame =
->print(frame)` for Python 3 compatibility.
Code Snippets
def add_frame(self,frame):
#Adds frame to end of list
self.frames.append(frame)
def remove_last_frame(self):
#Removes last frame in list
del self.frames[-1]
def clear_frames(self):
#Deletes all frames
del self.frames[:]
def get_frames(self):
#Returns list of frames
return self.framesdef run_animation(frames, loops, fps):
delay = 1.0 / fps
for _ in range(loops):
for frame in frames:
sp.call('clear',shell=True)
print(frame)
time.sleep(delay)Context
StackExchange Code Review Q#115903, answer score: 2
Revisions (0)
No revisions yet.