Why do we use @staticmethod?

I just don’t understand why we need to use @staticmethod. Start with an example.

class test1:
    def __init__(self,value):
        self.value=value

    @staticmethod
    def static_add_one(value):
        return value+1

    @property
    def new_val(self):
        self.value=self.static_add_one(self.value)
        return self.value


a=test1(3)
print(a.new_val) ## >>> 4



class test2:
    def __init__(self,value):
        self.value=value

    def static_add_one(self,value):
        return value+1

    @property
    def new_val(self):
        self.value=self.static_add_one(self.value)
        return self.value


b=test2(3)
print(b.new_val) ## >>> 4

In the above example, a method static_add_onein two classes does not require an instance of the class (self) in the calculation.

The method static_add_onein the class test1is decorated @staticmethodand works correctly.

But at the same time, a method static_add_onein a class test2that has no decoration @staticmethodalso works correctly, using a trick that provides an argument selfin the argument, but does not use it in everything.

So what is the advantage of using @staticmethod? Does performance improve? Or is it simply because of zen python that states that “Explicit is better than implicit”?

+4
4

staticmethod , -, ( - ), , - . (, , - , , .) - .

. , , self, static_add_one --- test2.static_add_one(1). , . "" - , self, .

+8

@staticmethod , , ( ).

test2.static_add_one self, , test1.static_add_one. , .

, , - Django, , . , , , , "slug", , URL. , slug, staticmethod, , .

0

@staticmethod.

static- , staticmethod.

,

class File1:
    def __init__(self, path):
        out=self.parse(path)

    def parse(self, path):
        ..parsing works..
        return x

class File2:
    def __init__(self, path):
        out=self.parse(path)

    @staticmethod
    def parse(path):
        ..parsing works..
        return x

if __name__=='__main__':
    path='abc.txt'
    File1.parse(path) #TypeError: unbound method parse() ....
    File2.parse(path) #Goal!!!!!!!!!!!!!!!!!!!!

parse File1 File2, . parse . File1, File1 parse. staticmethod File2 File2.parse.

.

0

, . , - . , (.. ) , , ( ). , , . , , self C.f C, :

  • . .

  • : , self.

  • , self, C f self.f, , f, .

2 ( self -- , ). , self ( , self). 3 @staticmethod .

0

Source: https://habr.com/ru/post/1539512/


All Articles