Skip to main content
 首页 » 编程设计

Python 问题之映射和类之初学者

2025年05月04日17oomusou

我正在尝试使用 Map 来引用类函数,但在格式化/排序方面遇到了困难。我听说使用 map 有点过时了,所以我绝对愿意接受替代解决方案(for loops?)提前致谢。

lognames =  [ "C:\Users\makker1\Desktop\logs\loga.txt", 
              "C:\Users\makker1\Desktop\logs\logb.txt", 
              "C:\Users\makker1\Desktop\logs\logc.txt" ] 
 
class LogFile: 
    def __init__(self,filepath): 
        self.logfile = open(filepath, "r") 
        self.head = None 
 
    def __str__(self): 
        return "x=" + str(self.x) + "y="+str(self.y) 
 
    def readline (self): 
        if self.head != None: 
            self.head = self.logfile.readline() 
 
    def previewline (self): 
        if self.head == None: 
            self.head = self.logfile.readline() 
 
    def close (self): 
        self.logfile.close() 
 
 
 
logs = map(LogFile(self,filepath).__init__(), lognames) 
heads = map(lambda log: None, logs) 
 
 
>>>  
Traceback (most recent call last): 
  File "C:\Users\makker1\Desktop\mergesort-final.py", line 30, in <module> 
    logs = map(LogFile(self,filepath).__init__, lognames) 
NameError: name 'self' is not defined 
>>>  

如果需要更多信息,请告诉我。我意识到有很多关于这个问题的帖子,并且已经对其中许多进行了分类但无济于事。

请您参考如下方法:

这是一个列表理解答案。我比 map() 更喜欢它。

logs = [LogFile(fname) for fname in lognames]