Static class methods

Chris Tavares ctavares at develop.com
Sun Mar 4 21:51:40 EST 2001


Try this:

>>> class Foo:
...     class FooMethods:
...             def foo1(self):
...                     print "FooMethods.foo1"
...     class_methods = FooMethods()
...
>>> foo = Foo()
>>> foo.class_methods.foo1()
FooMethods.foo1
>>> Foo.class_methods.foo1()
FooMethods.foo1
>>>

-Chris

"Alex Shindich" <alex at shindich.com> wrote in message
news:rdzo6.154$gc4.80445 at news.pacbell.net...
> 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