[Tutor] Declaring methods in modules.

Alan Gauld alan.gauld at btinternet.com
Sun Apr 11 17:58:04 CEST 2010


"Ray Parrish" <crp at cmc.net> wrote

> I am working on some stuff, and I would like to be able to write a module 
> which can be imported, and after it's been imported I would like to be 
> able to access it's functions as methods.

OK, Kind of...

> In other words, if I do the import of module ISPdetector, I want to then 
> be able to make calls like the following -
>
>    ipAddress = "123.123.123.123"
>    emails = ipAddress.GetEmailAddresses()

This won;t work since ipAddress is a string and you can't add methods to a 
builtin type.

But you could define a new special type of string class - an IPstring say - 
and
add methods to that. Put that definition in a module and you code becomes:

import ispdetector

ipAddress = ispdetector.IPstring("123.123.123.123")    # use module to 
access the class
emails = ipAddress.getEmailAddresses()         # use the locally created 
instance to access methods

> where GetEmailAddresses() is defined in module ISPdetector. Do I just 
> wite that function in ISPdetector.py as a normally deffed function, or 
> does it have to be part of a class within the module?

If you want to use it as a method it needs to be in a class. You could just 
write
it as a function that hass a string parameter in which case your code looks 
like:

import ispdetector

ipAddress = "123.123.123.123"
emails = ispdetector.getEmailAddresses(ipAddress)         # use the module 
and pass the strintg

Whether you need a class or not depends on what the restof your code is 
doing
and how data is being handled/stored etc. But we don;t have enough 
information
to be sure. My guess is that a class will be handy because you will likely 
need
several such methods all acting on common data - which is the definition of 
a class!

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list