jelly_bean
jelly_bean

Reputation: 89

What does a static method do in python?

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?

Upvotes: 0

Views: 177

Answers (2)

Daid Braam
Daid Braam

Reputation: 193

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'}")

Upvotes: 1

Roy Avidan
Roy Avidan

Reputation: 768

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()

Upvotes: 0

Related Questions