[英]How to get class method to update dictionary?
我正在嘗試制作一個靈活的參數解析器,該解析器接受字符串,在字符串中查找參數,並創建一個像這樣的字典:
message = "--mass=12"
physics = comparse(message, "mass", "int", 10, "this is your mass attribute")
產生: {'mass': 12}
我無法更新和添加更多參數/鍵(例如,如果我想添加“ vel”變量)到字典。 不幸的是,我是Python類的新手,盡管解析器檢測到第一個參數,但我無法添加到字典中。 這是我的程序:
import shlex
class comparse(object):
def __init__(self, message, attribute, var_type, default, help_txt):
self.data = {} #This is the "data" dictionary that this function will ultimately return.
self.message = message
self.attribute = attribute
self.var_type = var_type
self.default = default
self.help_txt = help_txt
#Remove unwanted symbols (e.g. "=", ":", etc.)
self.message = self.message.replace("=", " ")
self.message = self.message.replace(":", " ")
self.args = shlex.split(self.message)
def parse(self):
try:
options = {k.strip('-'): True if v.startswith('-') else v
for k,v in zip(self.args, self.args[1:]+["--"]) if k.startswith('-') or k.startswith('')}
if (self.var_type == "int"):
self.data[self.attribute] = int(options[self.attribute]) #Updates if "attribute" exists, else adds "attribute".
if (self.var_type == "str"):
self.data[self.attribute] = str(options[self.attribute]) #Updates if "attribute" exists, else adds "attribute".
except:
if self.attribute not in self.message:
if (self.var_type == "int"):
self.data[self.attribute] = int(self.default) #Updates if "x" exists, else adds "x".
if (self.var_type == "str"):
self.data[self.attribute] = str(self.default) #Updates if "x" exists, else adds "x".
return self.data
def add_argument(self):
self.data.update(self.data)
message = "-mass: 12 --vel= 18"
physics = comparse(message, "mass", "int", 10, "this is your mass attribute")
comparse.add_argument(message, "vel", "int", 10, "this is your velocity attribute")
print (physics.parse())
comparse.add_argument
方法不起作用。 顯然我做錯了,上課通常會使我感到困惑! 有人可以指出我的程序出了什么問題嗎?
我對您的班級設計感到有些困惑。 我以更全面的方式回答了這個問題,並提出了一些建議,建議您如何重新設計班級以更好地實現目標。
通常,當初始化一個類(您的解析器)時,您將為它傳遞完成其工作所需的所有數據。 但是,看來您的目標似乎是創建一個通用的物理解析器physics = comparse()
然后將可能的參數(例如質量和速度physics = comparse()
添加到物理解析器的數據中。 然后,給物理分析器一個消息字符串,例如message = "-mass: 12 --vel= 18"
,它應該對其進行語法分析並提取參數。 這表明您的代碼段的末尾是當前
message = "-mass: 12 --vel= 18"
physics = comparse(message, "mass", "int", 10, "this is your mass attribute")
comparse.add_argument(message, "vel", "int", 10, "this is your velocity attribute")
print (physics.parse())
應該看起來像這樣:
message = "-mass: 12 --vel= 18"
# create a parser
physics = comparse()
# tell the parser what arguments it should accept
comparse.add_argument("vel", "int", 10, "this is your velocity attribute")
comparse.add_argument("mass", "int", 10, "this is your mass attribute")
# give the parser a specific message for which it should extract arguments
print (physics.parse(message))
此代碼段將創建一個解析器,告訴解析器應接受哪些類型的參數(如速度和質量),然后從特定的字符串message
提取這些參數。
該設計更好地遵循了面向對象的編程原則。 這樣做的好處是,您正在創建一個可重用的physics
解析器,然后要求它解析未保存在其自身屬性中的字符串(無this.message
)。 這樣,您可以進行諸如physics.parse(“-mass:40 --vel = 15”)之類的其他調用,並重用物理解析器。
如果此設計更准確地符合您的意圖,那么我將通過以下方式修改代碼以使其遵循:
self.attribute, self.var_type, self.default, self.help_txt
只是單個變量,因此我將它們self.attribute, self.var_type, self.default, self.help_txt
可以添加屬性名稱,變量的數組類型,默認值和幫助文本作為EACH參數。 將它們初始化為init中的空數組,如下所示: self.defaults = []
。 我還將更改每個名稱,以表明它們是數組,而不是單個變量,因此使用默認值,類型,文本等。 將add_argument修改為以下內容:
def add_argument(自我屬性,var_type,默認值,help_txt):
self.attributes.append(屬性)
self.var_types.append(var_type)
self.defaults.append(默認)
self.help_txts.append(默認)
修改解析器以將message
作為參數,刪除其不需要的符號,執行拆分,然后對在add_argument中設置的每個參數執行其邏輯。
如果您有任何疑問,請發表評論,祝您好運!
在下面的代碼中
def add_argument(self):
self.data.update(self.data)
add_argument
不接受任何參數。但是,您已經完成了
comparse.add_argument(message, "vel", "int", 10, "this is your velocity attribute")
在這里您給出了多個參數。 這是問題的原因
要解決此問題,請嘗試修改add_argument函數以接受您希望它處理的參數
編輯:根據您的評論,該功能應該已經
def add_argument(self,message, attribute, var_type, default, help_txt):
data = comparse.parse(message, attribute, var_type, default, help_txt)
self.data.update(data)
但是,再一次,parse方法實際上在您的代碼中不帶任何參數,因此..修改它以接受您需要的所有參數以及self
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.