3
Contributors
2
Replies
27
Views
3 Years
Discussion Span
Last Post by vegaseat
1

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

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

    @classmethod
    def getCount(cls):
        return Foo.__count   

if __name__ == '__main__':
    Foo.bar()
    print(Foo.getCount())

Which should print 1.

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

0

Another example ...

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

class Foo2(object):
    def bar(self):
        print("Foobar2")
    bar = classmethod(bar)

# simpler via a decorator
class Foo3(object):
    @classmethod
    def bar(self):
        print "Foobar3"

Foo2.bar()  # Foobar2      
Foo3.bar()  # Foobar3  
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.