The question doesn't seem to make musch sense. One cannot 'run' a class in Python - a class is a collection of methods and instance variables, and cannot be exectued per se.

I suppose if you are coming from a Java perspective, one could see executing the main() function as 'running' the class, but Python has no equivalent to that - unlike in Java, is is possible (necessary, in fact) to have code outside of a class and run it separately.

The other possible interpretation of your question is, 'how can you have a class method and call it without instantiating the class as an object?', in which case the answer is simple. Class methods are indicate with the @classmethod decorator, like so:

class Foo:
    __count = 0

    def bar(cls):
        Foo.__count += 1

    def getCount(cls):
        return Foo.__count   

if __name__ == '__main__':

Which should print 1.

Do either of these answer your question? If not, please clarify what you want.

Another example ...

classmethod allows to call a method in the class Foo this way
normally it would be via the instance
class_instance = Foo()

class Foo2(object):
    def bar(self):
    bar = classmethod(bar)

# simpler via a decorator
class Foo3(object):
    def bar(self):
        print "Foobar3"  # Foobar2  # Foobar3  
This article has been dead for over six months. Start a new discussion instead.