faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 7 people (57%) answered Yes
Recently 1 of 2 people (50%) answered Yes

Entry

Static methods (was: Threading question)

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 244, Evan Simpson


"""
Packages: oop
"""
"""
>I'm trying to use the "threading" module (the one loosely based on Java).
>I need to create many worker threads that do the same job, but take their
>input from a central list.  I think this would be done in Java by
>declaring a synchronized, static method that would access a static
>variable.  Unfortunately, Python does not seem to support static methods
>across instances.  How would I go about implementing this in Python.
There *are* ways to spell static methods, none of them pretty.  Here's one:
"""
class StaticMethod:
  def __init__(self, klass, methodname):
    self.klass = klass
    self.function= (klass.__dict__[methodname],)
    setattr(klass, methodname, self)
  def __call__(self, *p, **np):
    return apply(self.function[0], (self.klass,)+p, np)
class test:
  x = None
  def mymethod(self, a):
    self.x = a
StaticMethod(test, "mymethod") # Make "mymethod" static in class test (and
                               # returns the result, if you care to keep it).
t = test()
t.x = "fred"
t.mymethod(1)
# Now t.x is "fred" and test.x is 1
test.mymethod(1)  #also works
"""
Mmmm... unaddressed threading issue
Evan Simpson
"""