singleton (newbie)
Larry Bates
lbates at swamisoft.com
Wed Aug 18 19:54:22 EDT 2004
Neil,
Three observations:
1) IMHO Python needs to be written as Python not as some
other language. I've rewritten your class below:
class B:
x = 0
y = 1
def foo():
print B.x
foo = staticmethod(foo)
def bar():
print B.y
B.y+=1
bar = staticmethod(bar)
if __name__ == "__main__":
B.foo()
B.bar()
B.foo()
B.bar()
B.bar()
2) I continue to read on c.l.p. about staticmethods and
just don't understand why anyone would use them. This
is how I learned to write this in Python. It seems that
they are some sort of "carryover" from another language.
I'd be the first to admit I don't understand the appeal,
so maybe they can be useful. I've just never needed them.
If I need a static function, I just write it that way.
I don't make it the method of a class object.
if you want x, y to be global across all instances of B:
class B:
x = 0
y = 1
def foo(self):
print self.x
def bar(self):
print self.y
self.y+=1
if __name__ == "__main__":
b=B()
b.foo()
b.bar()
b.foo()
b.bar()
b.bar()
if you want x, y to be local to current instance of B:
class B:
def __init__(self):
self.x=0
self.y=1
def foo(self):
print self.x
def bar(self):
print self.y
self.y+=1
if __name__ == "__main__":
b=B()
b.foo()
b.bar()
b.foo()
b.bar()
b.bar()
3) If you just want static functions, just write them that way.
def foo():
global x
print x
def bar():
global y
print y
if __name__ == "__main__":
x=0
y=0
foo()
bar()
foo()
bar()
bar()
Maybe it will help, maybe not.
Larry Bates
Syscon, Inc.
"Neil Zanella" <nzanella at cs.mun.ca> wrote in message
news:b68d2f19.0408181413.70f2a91b at posting.google.com...
> Hello,
>
> Is this the correct way to code multi-instance singleton in Python?
> It seems to do the trick for me but I appreciate any criticism as I
> am somewhat new to Python.
>
> Thanks,
>
> Neil
>
> #!/usr/bin/python
>
> class B:
> x = 0
> y = 1
> def foo(): print B.x
> foo = staticmethod(foo)
> def bar(): print B.y; B.y += 1
> bar = staticmethod(bar)
>
> if __name__ == "__main__":
> B.foo()
> B.bar()
> B.foo()
> B.bar()
> B.bar()
More information about the Python-list
mailing list