[Tutor] ftplib with classes
alan.gauld@bt.com
alan.gauld@bt.com
Tue, 27 Aug 2002 18:19:09 +0100
> I'm trying to get my hands dirty with using classes ...
> different story. Looking at the doc for ftplib I see:
>
> Now the code I have as of now is:
>
> import ftplib
>
> class Connection:
> def __init__(self, host='', user='', passwd='', acct=''):
> self.user = username
> self.host = hostname
> self.passwd = password
>
> Am I doing this right?
So far so good. You can now create a connection instance
and pass it the details it needs.
> Also, for connecting ( connect()) would I use
> that as a method?
You probably want to make it a method taking some parameters which are
defaulted to the self ones:
def connect(self, host=self.host,user=self.user,...etc)
You might also like to automatically connect within
the init method iff you have the requireddata.
Add after your code:
if self.host != '' and self.user != '' and...
self.connect()
Then whehn you come to use your class it looks like this:
import ftpClass
conn1 = ftpClass.Connection() # no connection made yet
conn2 = ftpClass.Connection('ftp.google.com', 'anonymous', 'me@foo.com')
conn1.connect('ftp.bigbiz.com','agauld', 'ninini')
files = conn1.ls()
theFile = conn1.get(files[0])
conn1.close()
conn2.put(files[0])
conn2.close()
And so on. In designing a class it's a good idea to run one
of these imaginary usage scenarios to help decide what
the methods should look like from the client perspective...
HTH,
Alan g.