[英]Python 3 - function data member of class
我有一類應該調用subprocess.call來運行腳本的工作。
我已經在模塊中定義了該類,並且在模塊頂部,我從子流程中導入了call函數。
我不確定是否應該只在類的函數之一中使用call(),還是應該使它成為數據成員,然后通過self.call函數對象進行調用。
我希望使用后者,但是我不確定該怎么做。 理想情況下,我不希望子進程位於頂部,而應具有以下內容:
class Base:
def __init__():
self.call = subprocess.call
但以上方法不起作用。 您將如何去做? 我是Python 3的新手。
您是不是要:
import subprocess
class Base:
def __init__(self): #don't forget `self`!!!
self.call = subprocess.call
instance = Base()
print (instance.call(['echo','foo']))
雖然我真的更喜歡:
import subprocess
class Base:
call = staticmethod(subprocess.call)
def __init__(self):
self.call(["echo","bar"])
instance = Base()
print (instance.call(['echo','foo']))
最后,如果您不需要將call
作為類的API的一部分,那么我認為最好在方法中使用subprocess.call
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.