Static methods in Python?

+1 vote

Is it possible to have static methods in Python so I can call them without initializing a class, like:

ClassName.StaticMethod ( )

Aug 1, 2018 in Python by bug_seeker
• 15,350 points
54 views

2 answers to this question.

0 votes

Yes this can be acheived by using staticmethod decorator

class MyClass(object):

   @staticmethod def the_static_method(x):

      print x MyClass.the_static_method(2

      # outputs 2

Note:-  Code might use the old method of defining a static method, using staticmethod as a function rather than a decorator. 

class MyClass(object):

   def the_static_method(x):

      print x the_static_method = staticmethod(the_static_method) 

      MyClass.the_static_method(2

      # outputs 2

This is entirely identical to the first example (using @staticmethod), just not using the nice decorator syntax.

answered Aug 1, 2018 by Priyaj
• 56,520 points
+1 vote
Static methods are used when we need to process data associated with classes instead of instances. A static method has no self argument and it is nested in a class and is designed to work on class attributes instead of instance attributes.Static methods never receive an automatic self argument, whether called through a class or an instance. They usually keep track of information that spans all instances, rather than providing behavior for instances.
answered Aug 4, 2018 by Ronaldobessmin
• 160 points

edited Aug 4, 2018 by Vardhan

Related Questions In Python

+1 vote
2 answers

Difference between append vs. extend list methods in Python

Python append() method adds an element to ...READ MORE

answered 3 days ago in Python by germyrinn
• 180 points
167 views
0 votes
1 answer

Difference between append vs. extend list methods in Python

append: Appends object at the end. x = ...READ MORE

answered Aug 8, 2018 in Python by bug_seeker
• 15,350 points
85 views
0 votes
1 answer

Pycharm warning: Must implement all abstract methods in Python. Why?

n vote As expected, python itself recognises that ...READ MORE

answered Nov 9, 2018 in Python by Nymeria
• 3,520 points
372 views
+3 votes
7 answers

How can I rename a file in Python?

yes, you can use "os.rename" for that. ...READ MORE

answered Mar 31, 2018 in Python by DareDev
• 6,810 points
115 views
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,420 points
80 views
+2 votes
3 answers

what is the practical use of polymorphism in Python?

Polymorphism is the ability to present the ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,420 points
1,215 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 175 views
+4 votes
6 answers