我编写了一个小程序,它将打印我指定的路径中的所有文件和目录。源代码是:
import os
import glob
class FolderStats:
targetdir = ""
def __init__(self, dirpath = None):
targetdir = dirpath
totalfiles = 0
totalsubfolders = 0
def FolderIterator(self):
print self.targetdir
listing = os.listdir(self.targetdir)
for infile in listing:
print "current file is: %s" % (infile)
if __name__ == '__main__':
Obj = FolderStats(raw_input('Enter your path: '))
Obj.FolderIterator()
以上代码未执行。我在方法FolderIterator
中收到错误:执行print命令时,它什么都没打印。 <targetdir>
不再包含我提供的路径。为什么会这样?
答案 0 :(得分:0)
在__init__
中,您需要使用self.targetdir
代替targetdir
>>> class Test:
var = 1
def __init__(self):
var = 2
print self.var # Object variable
print var # Local variable
def func(self):
print self.var
print var # this will fail, because there's no local var in this scope
>>> a = Test()
1
2
>>> a.func()
1
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
a.func()
File "<pyshell#10>", line 9, in func
print var
NameError: global name 'var' is not defined