s5s
s5s

Reputation: 12144

Python 3 - function data member of class

I have a class which should call subprocess.call to run a script as part of it's job.

I've defined the class in a module and at the top of the module I have imported the call function from subprocess.

I am not sure whether I should just use call() inside one of the functions of the class or whether I should make it a data member and then call it via the self.call function object.

I would prefer the latter but I'm not sure how to do this. Ideally I would like not to have subprocess at the top and have something like:

class Base:
    def __init__():
        self.call = subprocess.call

but the above doesn't work. How would you go about doing this? I'm very new to Python 3.

Upvotes: 0

Views: 196

Answers (1)

mgilson
mgilson

Reputation: 309929

Do you mean that you want:

import subprocess

class Base:
    def __init__(self):  #don't forget `self`!!!
        self.call = subprocess.call

instance = Base()
print (instance.call(['echo','foo']))

Although I would really prefer:

import subprocess

class Base:
    call = staticmethod(subprocess.call)
    def __init__(self):
        self.call(["echo","bar"])

instance = Base()
print (instance.call(['echo','foo']))

Finally, if you don't need to have call as part of your API for the class, I would argue it's better to just use subprocess.call within your methods.

Upvotes: 1

Related Questions