Consider the following class:
import subprocess
class Fruits():
def __init__(self):
self.TERMINAL_WIDTH = 80
def start(self):
p = subprocess.Popen(["mplayer", "other", "args"])
print "Subprocess started..."
This code works.
To gain some more insight in best coding practices, I'm using a PEP 8 linter for Python. The linter complains about the line
p = subprocess.Popen(["mplayer", "other", "args"])
: the linter says that because we're defining a variable (p
), it should probably go to the __init__()
method instead.
I'm wondering how to do this, though. If I transfer that line to __init__()
in its current form, the subprocess will start running when Fruits()
is instantiated, which is not what I want. Can you help me here?
At first you are creating a local variable. The is OK, but it is lost when the execution of the method has finished.
You most likely want to have an instance variable. Then the line has to look like this:
But also
p
is a poor choice of name, you should use something longer,mplayer_proc
for example.Then there is the convention to initialize all instance variables in
__init__
, it is not required but very helpful when you use an IDE. You don't need to give it a finial value. If you have nothing to store there while initializing, just set it toNone
: