我正在嘗試做代碼分析器應用程式,我有一個包含 python 代碼的 txt 檔案,我現在的目標是將這個 txt 檔案中的所有函式保存在類的字典中,但我不知道我該怎么做做
起初我創建了名字是class CodeAnalyzer:
def __init__(self, file):
self.file = file
self.file_string = ""
self.file_func= {}
self.errors = {}
我想將函式保存在self.file_func= {}
這是流程步驟,每個方法都應回傳添加到屬性的鍵和值
def process_file(self):
for i, line in enumerate(self.file):
self.file_string = line
self.check_divide_by_zero(i, line)
self.check_parameters_num(i, line)
這是我試圖做的,但失敗了:
def store_function(self,i,line):
if(line.startswith('def')):
self.file_func.setdefault(i,[]).append((self.file_string[file_string.index(':') ,:]))
任何人有一個想法或幫助嗎?
uj5u.com熱心網友回復:
您可以將exec()它的 globals() dict 設定為您的類實體的命名空間。
class CodeAnalyzer:
def __init__(self,file):
# Read a string from the file
f=open(file)
t=f.read()
f.close()
#Populate the namespace dictionary by executing the code in the file
self.namespace={}#this includes all declarations of functions, variables and classes
exec(t,self.namespace)#this means that when variables are declared, they use the class instance's attributes dictionary as their global namespace
#Filter the namespace dict based on the contents
self.functions={i:self.namespace[i] for i in self.namespace if isinstance(i,type(lambda:0))}#type(lambda:0) is just FunctionType
self.classes={i:self.namespace[i] for i in self.namespace if isinstance(i,type)}#all classes are instances of type
self.variables={i:self.namespace[i] for i in self.namespace if i not in self.functions|self.classes}#everything else, using dictionary merge
如果您還有其他問題,請隨時對此答案發表評論。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438694.html
標籤:Python python-3.x 列表 python-2.7 字典
上一篇:用平均值填充空值和下一個值
