[英]how to pass argparse arguments to a class
我對一般的代碼特別是Python還是很陌生的。 我正在嘗試學習如何將我創建的argparse參數傳遞到類中,以使用正確/推薦的方式。 除了學習python外,我還嘗試學習如何以OOP方式進行操作,以便學習其他OOP類型的語言變得容易一些。
因此,這是我要執行的操作的一個示例:
import argparse
class passyourcliargstome():
def __init__(self, whatdoiputheretogetmycliargs):
#how do I get my cli args here?
pass
def otherfunctionsthatdothings():
pass
if __name__ == '__main__':
#grab the arguments when the script is ran
parser = argparse.ArgumentParser(
description='Make things happen.')
parser.add_argument('-f', '--foo', action='store_true', default=False, help='here be dragons')
parser.add_argument('-b', '--bar', action='store_true', default=False, help='here be more dragons')
passyourcliargstome.otherfunctionsthatdothings()
因此,我要在主類之外定義argparse參數,並想知道如何將其放入類中。 這是正確的方法嗎? 我應該只讓argparse作為我班下的函數嗎?
預先感謝您的幫助,參考等。
編輯:11/16 2:18 EST
注意:由於我沒有足夠的代表來回答自己的問題,因此這是我發布適當答案的唯一途徑。
好的,這花了我一些時間,但我設法將其拼湊起來。 RyPeck的答案幫助我獲取了參數(缺少我的代碼),但是隨后,當我嘗試測試代碼時,我遇到了未綁定的方法錯誤。 我不知道那是什么意思。 我是否提到我不辜負自己的屏幕名稱?
直到我找到並閱讀這篇文章時,它才真正點擊。 這是我的工作代碼。 如果有人對此有任何補充,包括“您仍然做錯了,請以正確的方式這樣做”。 我全是耳朵。 同時,感謝您的幫助。
import argparse
class Passyourcliargstome(object):
def __init__(self):
#here's how I got my args here
self.foo = args.foo
self.bar = args.bar
def otherfunctionsthatdothings(self):
print "args inside of the main class:"
print self.foo
print self.bar
if __name__ == '__main__':
#grab the arguments when the script is ran
parser = argparse.ArgumentParser(description='Make things happen.')
parser.add_argument('-f', '--foo', action='store_true', default=False, help='here be dragons')
parser.add_argument('-b', '--bar', action='store_true', default=False, help='here be more dragons')
args = parser.parse_args()
print "args outside of main:"
print args.foo
print args.bar
#this was the part that I wasn't doing, creating an instance of my class.
shell = Passyourcliargstome()
shell.otherfunctionsthatdothings()
不帶任何參數運行此代碼將打印False四次。 在類實例之外兩次,在類實例內部兩次。
使用parser.parse_args
並將其與vars
一起包裝,以將特殊的argparse命名空間類型轉換為常規Python dict。 通常,您需要以下模式:
def main():
parser = argparse.ArgumentParser()
parser.add_argument('foo')
parser.add_argument('bar')
args = parser.parse_args()
args_dict = vars(args)
之后,您可以將參數顯式或全部傳遞給將采用它的任何類或函數。 對於類,最好顯式編寫所需的參數。 像這樣:
class MyClass(object):
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
def Print(self):
print self.foo
print self.bar
現在,您可以像這樣將這兩個部分放在一起:
import argparse
class MyClass(object):
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
def Print(self):
print self.foo
print self.bar
def main():
parser = argparse.ArgumentParser()
parser.add_argument('foo')
parser.add_argument('bar')
args = parser.parse_args()
c1 = MyClass(args.foo, args.bar)
args_dict = vars(args)
c2 = MyClass(**args_dict)
將同時創建c1
和c2
。 不過,最好的方法是像c1
一樣顯式地創建類。
一個簡單的for
循環可以傳遞參數(或設置您的屬性):
args_dict = vars(self.parser.parse_args())
# using argparse arguments as attributes of this (self) class
for item in args_dict:
setattr(self, item, args_dict[item])
但是...也許一種優雅的方法是使用argparse
初始化您的類,並通過名稱空間將它們直接設置為該類:
class Foo:
def __init__(self)
self.parser = ArgumentParser()
self.parser.add_argument('-f', '--foo, default=False, action='store_true', help='foo or not?')
self.parser.add_argument('-b', '--bar', default=0, action='store', help='set the bar')
self.parser.parse_args(namespace=self)
空輸入等效於:
class Foo:
def __init__(self)
self.foo = False
self.bar = 0
添加參數后,必須執行以下操作。
args = parser.parse_args()
如果在args上進行打印,則會看到名稱空間參數中包含所有參數。
然后,您可以像這樣訪問它們-
print args.foo
print args.bar
從那里,您可以像對待普通變量一樣對待它們。 有關更多詳細信息和更多信息,請參見argparse文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.