在过去的一年里,我对用python进行off编码感到很舒服,但是我没有去学习类(比如在它们中构造我的代码),因为我还没有理解它们。
我现在正试图把我的头脑集中在我的编码实践中需要改变的地方,以便充分利用类的所有优点。
我一直试图使用我编写的示例脚本,并将其转换为基于类的版本。可以肯定地说,我是吸坏了,不能让我的简单的脚本工作。我确信有很多这样的事情,我很可能做错了。我真的很感激有人指点给我看。
我不介意指尖和肚皮也笑了,^_^
编码后的(不工作)
"""
Description:
This script is used to walk a directory and print out each filename and directory including the full path.
Author: Name
Usage:
DirLister.py (-d <directory>)
DirLister.py -h | --help
DirLister.py --version
Options:
-d <directory> The top level directory you want to list files and directories from.
-h --help Show this screen.
--version Show version.
"""
import os
from docopt import docopt
class walking:
def __init__(self, directory):
self.directory = arguments['-d']
def walk(self, directory):
for root, dirs, files in os.walk(self.directory):
for filename in files:
print os.path.join(root, filename)
if __name__ == '__main__':
arguments = docopt(__doc__, version= '1.0.0')
print arguments
if arguments['-d'] is None:
print __doc__
exit(0)
else:
walking.walk(directory)原始非类代码(工作)
"""
Description:
This script is used to walk a directory and print out each filename and directory including the full path.
Author: Name
Usage:
DirLister.py (-d <directory>)
DirLister.py -h | --help
DirLister.py --version
Options:
-d <directory> The top level directory you want to list files and directories from.
-h --help Show this screen.
--version Show version.
"""
import os
from docopt import docopt
arguments = docopt(__doc__, version= '1.0.0')
def walk(dir):
for root, dirs, files in os.walk(dir):
for filename in files:
print os.path.join(root, filename)
if __name__ == '__main__':
if arguments['-d'] is None:
print __doc__
exit(0)
else:
walk(arguments['-d'])发布于 2015-03-25 17:53:03
您已经忘记发布您得到的错误(因为您说它不起作用)。
但确实有几个问题。首先,我把类称为Walking。
然后,在__init__函数中,尝试访问既不是全局变量也不是参数的arguments;您想要编写:
def __init__(self, directory):
self.directory = directory但是,还需要在main中创建类的实例。
walking = Walking(arguments['-d'])它假设类的名称是Walking而不是walking。我建议您查看PEP8的命名约定。
总的思想是,类是对象的类型,而不是对象本身*,因此class Walking:块基本上定义了一种新的对象类型。然后,您可以创建作为该类实例的对象。当您创建一个list:mylist = list()时,情况也是一样的(但是对于mylist = [1, 2]这样的列表也有其他的方法)。
* Python中的大多数东西都是对象,包括类,但它们显然有其他方法,并且有另一个基类。
https://stackoverflow.com/questions/29262939
复制相似问题