Factory functions?
Roy Smith
roy at panix.com
Sun Apr 1 10:30:09 EDT 2001
Typically, when I write a new class module, I'll call the class the same
name as the module, and then create objects of that class by doing:
import foo
myFooObject = foo.foo()
I've always found this kind of awkward and ugly, and somewhat confusing,
especially when the names are kind of long, i.e.
myFrobnitz = reverseIteratorFrobnitz.reverseIteratorFrobnitz()
It seems to me, you could "solve" this problem (I put "solve" in quotes
because I'm not yet really convinced there's a problem that needs solving)
by using a factory function, i.e.
-----file reverseIteratorFrobnitz.py-----
import iteratorFrobnitz
class reverseIteratorFrobnitz (iteratorFrobnitz.iteratorFrobnitz):
def __init__ (self, name):
self.name = name;
self.interationSense = -1
def new (name):
return reverseIteratorFrobnitz (name)
-----------------------------------------
Then when I want to use one of these, I just do:
import reverseIteratorFrobnitz
myFrobnitz = reverseIteratorFrobnitz.new ("Dinsdale")
What are the pros and cons of doing it one way or the other (i.e. calling
the built-in class creator directly, or calling a trivial factory function
to create an object for you and return it). Is it really just a matter of
style and esthetics more than anything else?
More information about the Python-list
mailing list