0

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 2

1

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'}")
Sign up to request clarification or add additional context in comments.

3 Comments

But why would you create a specific object inside a method and then create another object outside of it? i.e result and object1
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".
(If you are asking questions like this, I assume you're not fully grasping the concept of variables and how objects work yet)
0

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

a.func2() still would work, so maybe not the best example
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.