[Tutor] Subclassing vs. stand alone functions
jorgen.maillist at gmail.com
Fri Jun 15 15:31:29 CEST 2007
Basically you write a (sub)class when you want to preserve state
information of your instance. If the functionality in question lives
longer then the scope of the function, and will be called from
different methods to obtain the same information and state of the
functionality at that time, it is a candidate for a class.
Whenever the class lives very short, and there is no chance that
seperate threads might screw up the state of the functionality, it is
usually sufficient to keep it inside a module.
On 6/15/07, chrispython at mac.com <chrispython at mac.com> wrote:
> Hi there,
> I am new to Python and trying to get my head around the OO stuff. I guess my question is - when do you go with subclassing vs. making a standalone function?
> Let's say you want to load a dictionary. Do I create a function that accepts some argument (say a file name) and returns a dictionary, or do I subclass dict and override the __init__ and __setitem__ functions to make 'self-loading' dictionary? It seems the end result is the same.
> Here is a follow-up if you will indulge me...
> I created a class called WebPage which is a stand-alone class (I get that). It loads a web page template, and has a function to update the replacement vars with your data (updHtmlVar), and another to spit out the html to a file (wrtHtml). Do you subclass WebPage for each particular page you want (because you can customize it with load functions for each piece of data) or do you just use it as is, and create separate functions outside the class that load the data and you just use updHtmlVar to load it into your WebPage object? Again, the end result is the same.
> (I can send code samples if it will help).
> Tutor maillist - Tutor at python.org
More information about the Tutor