how do I run a python class without creating an object

Recommended Answers

All 2 Replies

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.

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  
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.