[Tutor] Declaring methods in modules.
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 = "18.104.22.168"
> emails = ipAddress.GetEmailAddresses()
This won;t work since ipAddress is a string and you can't add methods to a
But you could define a new special type of string class - an IPstring say -
add methods to that. Put that definition in a module and you code becomes:
ipAddress = ispdetector.IPstring("22.214.171.124") # 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
it as a function that hass a string parameter in which case your code looks
ipAddress = "126.96.36.199"
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
and how data is being handled/stored etc. But we don;t have enough
to be sure. My guess is that a class will be handy because you will likely
several such methods all acting on common data - which is the definition of
Author of the Learn to Program web site
More information about the Tutor