Static class methods
Alex Shindich
alex at shindich.com
Sun Mar 4 17:22:10 EST 2001
Just out of my curiosity, have any of you ladies and gentlemen experienced a
need for an equivalent of C++/Java static method?
Because I have, but it is impossible add them to Python classes -- all class
methods are treated as instance methods.
This is especially unfortunate given that local functions now work properly
thanks to PEP 227.
I was thinking that a new keyword "unbound" could be used to identify
functions that belong to a class but do not expect "self" as their first
attribute.
>From outside the class "unbound" methods would be invoked by specifying the
class name -- Foo.my_static_method (). From within the class they would work
similar to local functions that are defined at the class level. The __ trick
should work for the "unbound" methods as well to allow for creation of
private static methods.
Examples:
>>>class Foo:
"""This is a sample class..."""
__myPrivateStaticVariable = None
unbound getMyPrivateStaticVariable ():
"""getMyPrivateStaticVariable (obj) -> obj
This method returns the value stored in private static variable...
"""
return Foo.__myPrivateStaticVariable
unbound modifyMyPrivateStaticVariable (obj):
"""modifyMyPrivateStaticVariable (obj) -> void
This method assigns obj to the private static variable...
"""
Foo.__myPrivateStaticVariable = obj
>>> type (Foo.modifyMyPrivateStaticVariable)
<type 'unbound method'>
>>> type (Foo.getMyPrivateStaticVariable ())
<type 'None'>
>>> Foo.modifyMyPrivateStaticVariable ("abc")
>>> Foo.getMyPrivateStaticVariable ()
"abc"
>>>
More information about the Python-list
mailing list