"static" class functions?

Pete Shinners pete at visionart.com
Tue May 22 20:34:46 EDT 2001


"Neil" <mac4-devnull at theory.org> wrote 
> I am interested in having a function associated with a class that can be
> run without an instance of the class.

hello neil. i also have wanted this. and after digging around
in the python code, found it's actually easier for python to do
it than not. i've submitted a patch to python to "fix" this, but
i fear it will not be the implementation that keeps this from
being applied.

the only way to really do it currently is to wrap the "static"
function in a class that "unwraps" the object call...

class StaticFunc:
    def __init__(self, func):
        self.func= func
    def __call__(self, *args, **kwargs):
        self.func(*args, **kwargs)

class Foo:
    __val = 5
    def _printPrivate():
        print Foo.__val
    printPrivate = StaticFunc(_printPrivate)


there you go. from "outside" your class it works just as expected,
from "inside" your class it is a bit ugly. in the meantime, maybe
with enough positive feedback we can push this through...

http://sourceforge.net/tracker/index.php?func=detail&aid=418390&group_id=5470&atid=305470

(it makes your previous code example work as-is, and as-expected)





More information about the Python-list mailing list