Living without static member functions

Sami Hangaslammi shang.remove_edu at st.jyu.fi.edu
Mon Jan 24 09:24:33 EST 2000


On 24-Jan-00 Richard Brodie wrote:

<snip>

>  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?

Well, you don't have to take allMilken out of the class scope, just
the find function. i.e. I would write your class like this:

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

def Milkman_find(name):
    return Milkman.allMilkmen[name]

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

>>> from test import Milkman
>>> dir(Milkman)
['__doc__', '__init__', '__module__', 'allMilkmen']


Mikael Olofsson <mikael at isy.liu.se> wrote in message
news:XFMail.000124133458.mikael at isy.liu.se...

<snip>

> 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).

Because objects use reference semantics, Mattias does NOT replace
Mikael. The only thing changed is the local variable 'a' which now
referes to another object. If you do not intend to keep the objects in
the dictionary after they are not referenced from anywhere outside the
dictionary, you can add the following function:

def Milkman_clear():
    from sys import getrefcount
    dict = Milkman.allMilkmen
    for k in dict.keys():
        # if the number of references is two (one from
        # Milkman.allMilkmen and the other because the
        # object is the parameter to the getrefcount
        # function), remove the object from the dictionary
        if getrefcount(dict[k]) == 2:
            del dict[k]

> Perhaps you could make it more obvious by declaring it as global
> inside the class:

NOTE: The below code does not declare allMilkmen as global inside the
class, but as global inside the module.

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

--
Sami Hangaslammi
shang (at) st (dot) jyu (dot) fi

Get paid to surf the Web!
http://www.alladvantage.com/home.asp?refid=BOT021





More information about the Python-list mailing list