[Tutor] Py 2.4.4: Inheriting from ftplib.FTP()

Steven D'Aprano steve at pearwood.info
Fri Jun 17 11:31:41 EDT 2016


Some futher thoughts:

On Thu, Jun 16, 2016 at 10:38:13AM -0500, boB Stepp wrote:
> class FTPFiles(FTP, object):
>     """FTP files to Windows server location(s)."""
> 
>     def __init__(self, host=server_ip, user=user, passwd=passwd):
>         """Initialize FTPFiles object.  Normally the defaults will be used."""
> 
>         super(FTPFiles, self).__init__(host, user, passwd)
>         self.host = host
>         self.user = user
>         self.passwd = passwd

Do you actually need to record these? Once they're used to establish a 
connection and login, what are they for?


>     def print_welcome_msg(self):
>         """Print welcome message sent by FTP server."""
>         print self.getwelcome()

The getwelcome method already prints the message, which is a bad design. 
But only if debugging is true. So I would approach this in one of two 
ways:

(1) Delegate to the existing getwelcome method:

def print_welcome_msg(self):
    save_flag = self.debugging
    self.debugging = True
    try:
        x = self.getwelcome()  # prints the msg
    finally:
        self.debugging = save_flag


(2) Re-implement the print functionality.

def print_welcome_msg(self):
    print "*welcome*", self.welcome


(3) If you really want to be paranoid, use:

    print "*welcome*", self.sanitize(self.welcome)


although I don't think it's likely to make any real difference in 
practice.

(The sanitize method makes a feeble attempt to hide the password.)




> if __name__ == '__main__':
>     ftp = FTPFiles()
>     ftp.print_welcome_msg()
>     ftp.quit()

This appears to be equivalent to:

ftp = FTP(host, user, passwd)
ftp.debugging = True
x = ftp.getwelcome()
ftp.quit()




> What I learned today:
> 
> 1)  FTP from ftplib appears to be an old-style class.
> 
> 2)  I can't just use "class FTPFiles(FTP)" or I will be using old-style classes.

Is this a problem? Old-style classes are good enough for many purposes.

> 3)  I need to use "class FTPFiles(FTP, object)" to use new-style
> classes and "object" must come AFTER "FTP".
> 
> 4)  I have to use "super(FTPFiles, self).__init__(host, user, passwd)"
> or I cannot successfully inherit from the FTP() class.  Also, "self"
> apparently must come AFTER "FTPFiles" in the super expression.

For old-style classes, don't use super because it doesn't work. Instead 
just write:

    FTP.__init__(self, host, user, passwd)


That means that you cannot engage in multiple inheritence with new-style 
classes, but MI is a serious pain to get right, and 99% of the time it 
is overkill, so you're not missing much.



-- 
Steve


More information about the Tutor mailing list