Living without static member functions

Skip Montanaro skip at mojam.com
Mon Jan 24 11:35:40 EST 2000


    Richard> There's a programming quirk of mine that I haven't seen
    Richard> elsewhere, although probably well-known to some of you. Here's
    Richard> a rough outline of the code:

    Richard> class Milkman:

    Richard>     allMilkmen = {}

    Richard>     def __init__(self, name):
    Richard>         ...
    Richard>         allMilkmen[name] = self

    Richard>     def find(self, name):
    Richard>         return(allMilkmen[name])

I think what you are looking for here is

    class Milkman:

        allMilkmen = {}
    
        def __init__(self, name):
            ...
            MilkMan.allMilkmen[name] = self
    
        def find(self, name):
            return(Milkman.allMilkmen[name])

(That is, you need to reference the allMilkmen attribute via the class.  It
doesn't stand alone.)

    Richard> Firstly, I'm curious if this is well-known, useful or
    Richard> boneheaded design on my part.

It's useful in certain circumstances but does create circular references
between the class and its instances that you will have to break explicitly.
Instead of a Milkman instance just disappearing when it goes out of scope,
you'll have to define (and call) a destroy method that executes:

    del Milkman.allMilkmen[name]

    Richard> Secondly, it doesn't work in Python, of course, because I need
    Richard> a Milkman to find all the others (i.e. Milkman.find['Phil']
    Richard> doesn't work).  I can do something similar by taking allMilkmen
    Richard> and find to module scope; that seems kind of ugly, and worries
    Richard> me that I'm abusing the language. Can I do better?

How about:

    Milkman().find("Bob")

?  If you do that, modify __init__ to be

    def __init__(self, name=None):
	...
	if name is not None:
	    MilkMan.allMilkmen[name] = self

to avoid creating and having to destroy the circular reference.

    Richard> Thirdly, is there some neat way that I can find all members of
    Richard> a class by inquiring of the Python internals?

That would require classes to maintain references to all their instances
behind the scenes.  That, in turn, would generate the same circular
references that you have in your code, but not give the user any way to
delete it.

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/
847-971-7098






More information about the Python-list mailing list