我怎样才能反对一个简单的网站复制应用程序?

时间:2014-09-30 09:20:55

标签: python oop design-patterns object-oriented-analysis

直截了当,我是面向对象编程的新手,在学习Python时,我编写了一个简单的程序程序,它接受一个URL并将URL中的数据提取到文本文件中。

代码看起来像这样, 只是忽略了它们的组合!!

def open_URL(url):
    # try the URL
    # except errors

def fetch_raw_content(url):
    # fetch the raw content from web
    # return raw_content

def clean_up_raw(raw_content):
    # clean up html tags and stuff
    # format the raw content
    # return content

def write_to_file(filename, content):
    # create a file with filename
    # open the file
    # write the content
    # close the file


raw = fetch_raw_content(open(open_URL("somesite.com")))

content = clean_up_raw(raw)
write_to_file(content)

我想知道我是否可以这样做是一种面向对象的方式,因为我对面向对象世界的曝光是有限的,如果有人建议我某种方式我可以反对这个程序,谢谢。 :)

1 个答案:

答案 0 :(得分:0)

OOP是一种用于修复代码设计问题的工具。您的设计没有问题,没有什么可以解决的。如果你真的需要更抽象和可配置的代码,OOP只会为自己付出代价。例如,稍后您可能会意识到您的“内容”可以从不同的来源获得,而不仅仅是URL - 文件,数据库等。在这种情况下,您可以通过创建抽象类来{oopify'阅读部分{{ 1}}并为每种类型的来源制作特定的“读者”:

Reader

同样,如果您的“清理”过程可以分阶段拆分,并且您希望仅在特定情况下应用其中一些,则可以像这样抽象它:

 class Reader:
     def read():
        # return the content

 class URLReader(Reader)...

 class FileReader(Reader)...

 class DatabaseReader(Reader)...

然后:

 class Action:
    def apply(content):
        # apply the action to the content

 class RemoveWhiteSpace(Action)...

 class RemoveFontTags(Action)...

 class OptimizeLineBreaks(Action)...

 class Sequence(Action)...

然而,如果你真的需要那么大的灵活性,这些努力只能为自己付出代价。在大多数情况下,您可以在不使用 content = Sequence(RemoveWhiteSpace(), OptimizeLineBreaks()).apply(content) 关键字的情况下解决Python中的任何问题。