Docopt和Classes

时间:2015-03-25 17:50:03

标签: class python-2.7

在过去的一年中,我已经非常舒服地使用python进行编码了,但是我远离了Classes(就像在我们的代码中构造代码一样),因为我还没有理解它们。

我现在正试图了解我在编码实践中需要改变的内容,以利用他们所有荣耀中的类。

我一直在尝试使用我编写的示例脚本并将其传递给基于类的版本。可以说我糟透了,不能让我的简单脚本工作。我确定有无数的这种Im很可能做错了。我真的很感激有人指出他们。

我不介意手指点和肚子笑也是^ _ ^

编码后(不工作)

"""
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'])

1 个答案:

答案 0 :(得分:1)

您忘记发布错误(因为您说它不起作用)。

但确实有几个问题。首先,我打电话给班级Walking

然后在__init__函数中,您尝试访问既不是全局变量也不是参数的arguments;你想写:

def __init__(self, directory):
    self.directory = directory

但您还需要在main创建班级实例:

walking = Walking(arguments['-d'])

假设该类的名称为Walking而不是walking。我建议你查看PEP8的命名约定。

一般的想法是类是对象的类型,而不是对象本身*,因此class Walking:块基本上定义了一种新类型的对象。然后,您可以创建作为此类实例的对象。创建列表时也是如此:mylist = list()(但mylist = [1, 2]等列表还有其他方法。)

*碰巧Python中的大多数东西都是对象,包括类,但它们显然有其他方法,并且它们有另一个基类。