I'm currently learning about Python and am new to it. I've come across the OOP concept and am still confused about the main purpose of a static method. I'm not able to visualize the practicality of it or when I should use it (when needed). Does anyone know what this does and when I should use it?
2 Answers
A common use case for static methods is specific object creation.
For example, if you have an class A, that can be initialized from string data. But the string data can be xml or json. You can see something like:
class A:
@staticmethod
def fromXml(string):
result = A()
result.data = ...parseXML...
return result
@staticmethod
def fromJson(string):
result = A()
result.data = ...parseJson...
return result
And then use it like:
object1 = A.fromXml("<xml><data>hello</data></xml>")
object2 = B.fromJson("{'data': 'hello'}")
3 Comments
jelly_bean
But why would you create a specific object inside a method and then create another object outside of it? i.e result and object1
Daid Braam
It's not creating 2 objects. It's only creating a single object, and that's stored first in the name "result" inside the function, then returned, and then stored in the variable name "object1".
Daid Braam
(If you are asking questions like this, I assume you're not fully grasping the concept of variables and how objects work yet)
A static method is a method that doesn't use the class instance (the self parameter).
Let's say you have a class like this:
class test:
def func1(self): print('hello ' + self.name)
@staticmethod
def func2(): print('hello')
a = test()
a.name = 'PyCoder'
then you will call func1 with an instance of test, for example: a.func1()
func2 is static so it doesn't need an instance, and you will call it with the type name.
for example: test.func2()
2 Comments
OneCricketeer
a.func2() still would work, so maybe not the best example
mike3996
This is good summary of what they are, but because Python also has self-standing functions that should be preferred when the functionality has nothing to do with the class, Daid's answer cuts better into the jist