[Tutor] Tips
Steven D'Aprano
steve at pearwood.info
Thu Jun 19 03:37:22 CEST 2014
On Wed, Jun 18, 2014 at 12:35:20PM +0200, Sydney Shall wrote:
> On 17/06/2014 22:35, Alan Gauld wrote:
> >Use modules instead of singleton classes
> As a new beginner with Python, I am having problem understanding the
> difference here.
> I think I understand classes, but still have problems with inheritance,
> but I do not understand what defines a module.
I assume you know how to make a class:
class Spam:
def method(self, arg):
...
And then you make instances:
x = Spam()
y = Spam()
A singleton class is one which only allows there to be a single
instance (or occasionally, two instances, a "doubleton" class).
For example, None is a singleton. Like all instances, None has a class,
but see what happens if you try to create a second instance in Python
2.7 (Python 3.3 is slightly different):
py> from types import NoneType
py> x = NoneType() # create a new instance
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create 'NoneType' instances
The error is slightly inaccurate, it's not that no instances can be
created at all, but that only *one* instance can be created, and it's
already created and named None.
Inheritence is a separate issue, big enough that it deserves a new
thread.
As for modules, you already use modules, I'm sure, you just don't
realise it. Every time you create a python file ending in .py, that's a
module. Scripts are modules. Every time you use the import command,
you're loading a module:
py> import math
py> print math
<module 'math' from '/usr/local/lib/python2.7/lib-dynload/math.so'>
Python tries very hard to ensure that every module is loaded only once.
(There are circumstances where you can fool it, but they're rare.) Since
the module holds state (variables) and behaviour (functions), modules
perform the same sort of role as classes, so a module which is loaded
once is very similar to a singleton instance. In other words, if you
want a class to implement singleton behaviour, you have to work at it.
But if you shift the functionality from the class into a module, Python
gives you singleton behaviour for free.
But if you're not sure why anyone would want a singleton instance, I
agree with you: most (but not all) uses of singletons are unnecessary.
--
Steven
More information about the Tutor
mailing list