Question about Object Oriented + functions/global vars?

wittempj@hotmail.com martin.witte at gmail.com
Mon Jun 6 12:12:56 EDT 2005


Well, if you want to apply object orientatation techniques to your work
you would get something like this. Polymorphism is used to distinct
between the ftp method. Another concept is data encapsulation, see the
filedescription class . A third technique is inheritance - ftp is
derived from an existing object, the get classes are derived from my
ftp class.

But most of all it is a different way of organizing your work, for your
code I think it makes sense to split the work between an ftp class and
a filedescrition class - where you can add methods to record the status
of the retrieval.

#!/usr/bin/env python
import ftplib
import os.path
import sys

class ftp_err(Exception):
    pass

class ftp(ftplib.FTP):
    def __init__(self, address, filedescription, user = None, password
= None):
        ftplib.FTP.__init__(self, address)
        self.login(user, password)
        self.filedescription = filedescription

    def list(self):
        return self.nlst()

    def cd(self, directory):
        self.cwd(directory)

    def quit(self):
        self.quit()

class ftp_get(ftp):
    def get(self):
        cmd = 'RETR %s' % self.filedescription.name
        self.retrlines(cmd, open(self.filedescription.name, 'w').write)

class ftp_get_binary(ftp):
    def get(self):
        cmd = 'RETR %s' % self.filedescription.name
        self.retrbinary(cmd, open(self.filedescription.name,
'wb').write)

class filedescription(object):
    def set_name(self, name):
        self.__name = name
    def get_name(self):
        return self.__name
    name = property(get_name, set_name)

    def _get_texttype(self):
        ext = os.path.splitext(self.name)[1]
        if ext in ('.txt', '.htm', '.html'):
            return True
        else:
            return False

    def get_texttype(self):
        return self._get_texttype()
    text = property(get_texttype)

    def get_binarytype(self):
        return not self._get_texttype()
    binary = property(get_binarytype)

f1 = filedescription()
f1.name = 'download.ht'
f2 = filedescription()
f2.name = 'download.html'

ftp_site = 'ftp.python.org'
ftp_dir = 'pub/docs.python.org'

for i in (f1, f2):
    try:
        f = None
        if i.text:
            f = ftp_get(ftp_site, i)
        elif i.binary:
            f = ftp_get_binary(ftp_site, i)
        f.cd(ftp_dir)
        f.get()
    except Exception, e:
        print >> sys.stderr, '%s: %s' % (e.__class__.__name__, e)




More information about the Python-list mailing list