Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
3 views
in Python by (2.6k points)
edited by

Can someone tell me a static method in python, I don't want to use initialize a class like this to call them:

ClassName.StaticMethod ( )

2 Answers

0 votes
by (46k points)
edited by

You can use staticmethod decorator, look at the code below for instance:

class MyClass(object):
    @staticmethod
    def the_static_method(y):
        print y

MyClass.the_static_method(2) # outputs 2

For Python version 2.2 and 2.3:

 class MyClass(object):

    def the_static_method(y):
        print y
    the_static_method = staticmethod(the_static_method)

MyClass.the_static_method(2) # outputs 2

Hope this helps. Happy learning. 

If you are looking for upskilling yourself in python you can join our Python Training and learn from the industry expert.

0 votes
by (106k points)

You can check out the static method decorator:

>>> class C:

...     @staticmethod

...     def hello():

...             print "Hello World"

...

>>> C.hello()

Hello World

You can use the following video tutorials to clear all your doubts:-

Related questions

Browse Categories

...