Living without static member functions

Mikael Olofsson mikael at isy.liu.se
Mon Jan 24 07:34:58 EST 2000


On 24-Jan-00 Richard Brodie wrote:
 >  class Milkman:
 >  
 >      allMilkmen = {}
 >  
 >      def __init__(self, name):
 >          ...
 >          allMilkmen[name] = self
 >  
 >      def find(self, name):
 >          return(allMilkmen[name])
 >  
 >  It's handy for debugging or garbage collecting like activities. Also
 >  for distributed applications, where it's harder to keep object references
 >  around.
 >  
 >  Firstly, I'm curious if this is well-known, useful or boneheaded design
 >  on my part.
 >  
 >  Secondly, it doesn't work in Python, of course, because I need a
 >  Milkman to find all the others (i.e. Milkman.find['Phil'] doesn't work).
 >  I can do something similar by taking allMilkmen and find to module
 >  scope; that seems kind of ugly, and worries me that I'm abusing the
 >  language. Can I do better?
 >  
 >  Thirdly, is there some neat way that I can find all members of a class
 >  by inquiring of the Python internals?

FWIW, if you move allMilkmen outside of the class, you at least get something
that works:

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

But then again, that may not be what you want. If you do

a=Milkman('Mikael')
b=Milkman('David')
a=Milkman('Mattias')

then allMilkmen would be 

{'Mikael': <__main__.Milkman instance at e0f68>, 
'David': <__main__.Milkman instance at e0de8>, 
'Mattias': <__main__.Milkman instance at e0aa0>}

Hence, allMilkmen still keeps a reference to the first instance (Mikael), 
which has been replace by the third (Mattias). Plus, you have the risk
of accidentally doing something with allMilkmen without touching any
instance of Milkman, since it is not obvious that allMilkmen is actually
closely related to Milkman. Perhaps you could make it more obvious by
declaring it as global inside the class:

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

Then again, I might just be spreading crap.

/Mikael

-----------------------------------------------------------------------
E-Mail:  Mikael Olofsson <mikael at isy.liu.se>
WWW:     http://www.dtr.isy.liu.se/dtr/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
Date:    24-Jan-00
Time:    13:14:27

This message was sent by XF-Mail.
-----------------------------------------------------------------------



More information about the Python-list mailing list