-1

我编写了一个小程序,它将打印我指定的路径内的所有文件和目录。源代码是:

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:执行打印命令时,它什么也不打印。<targetdir>不再包含我提供的路径。为什么会这样?

4

1 回答 1

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
于 2013-02-08T05:53:05.197 回答