简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM