我正在尝试编写一个 FileAnalyzer 类,该类将在目录中搜索 Python 文件,并以 PrettyTable 的形式提供每个 Python 文件的详细信息。我对每个 Python 文件中的类、函数、行和字符的数量感兴趣。
学习 OOP 的原理......这是我到目前为止的代码:
class FileAnalyzer:
def __init__(self, directory: str) -> None:
"""
The files_summary attribute stores the summarized data for each Python file in the specified directory.
"""
self.directory: str = os.listdir(directory) #Directory to be scanned
self.analyze_files() # summarize the python files data
self.files_summary: Dict[str, Dict[str, int]] = {
dir: {
'Number of Classes': cls,
'Number of Functions': funccount,
'Number of Lines of Code': codelines,
'Number of Characters': characters
}
}
def analyze_files(self) -> None:
"""
This method scans a directory for python files. For every python file, it determines the number of classes,
functions, lines of code, and characters. The count for each one is returned in a tuple.
"""
for dir in self.directory:
if dir.endswith('.py'): # Check for python files
with open(dir, "r") as pyfile:
cls = 0 # Initialize classes count
for line in pyfile:
if line.startswith('Class'):
cls += 1
funccount = 0 # Initialize function count
for line in pyfile:
if line.startswith('def'):
funccount += 1
#Get number of lines of code
i = -1 #Account for empty files
for i, line in enumerate(pyfile):
pass
codelines = i + 1
#Get number of characters
characters = 0
characters += sum(len(line) for line in pyfile)
return [cls, funccount, codelines, characters]
def pretty_print(self) -> None:
"""
This method creates a table with the desired counts from the Python files using the PrettyTable module.
"""
pt: PrettyTable = PrettyTable(field_names=['# of Classes', '# of Functions', '# Lines of Code (Excluding Comments)',
'# of characters in file (Including Comments)'])
for cls, funccount, codelines, characters in self.files_summary():
pt.add_row([cls, funccount, codelines, characters])
print(pt)
FileAnalyzer('/path/to/directory/withpythonfiles')
NameError: name 'cls' is not defined
目前在我尝试运行代码时出现错误。调用self.analyze_files()
inside__init__
不足以将返回的值传递给__init__
? 理想情况下,对于一个 python 文件
def func1():
pass
def func2():
pass
class Foo:
def __init__(self):
pass
class Bar:
def __init__(self):
pass
if __name__ == "__main__":
main()
PrettyTable 会告诉我有 2 个类、4 个函数、25 行和 270 个字符。对于以下文件:
definitely not function
This is def not a function def
PrettyTable 会告诉我该文件有 0 个函数。我想self.analyze_files()
在self.files_summary
不将任何其他参数传递给analyze_files()
. 同样,将数据从files_summary
to传递给pretty_print
没有单独的参数传递给pretty_print
.
编辑:
self.files_summary: Dict[str, Dict[str, int]] = {
dir: {
'Number of Classes': self.analyze_files()[0],
'Number of Functions': self.analyze_files()[1],
'Number of Lines of Code': self.analyze_files()[2],
'Number of Characters': self.analyze_files()[3]
}
}
压制了错误,但是
for self.analyze_files()[0], self.analyze_files()[1], self.analyze_files()[2], self.analyze_files()[3] in self.files_summary():
pt.add_row([self.analyze_files()[0], self.analyze_files()[1], self.analyze_files()[2], self.analyze_files()[3]])
return pt
当我调用 FileAnalyzer 时inpretty_print
什么也没做...