Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

python - Why do we use @staticmethod?

I just can't see why do we need to use @staticmethod. Let's start with an exmaple.

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 example above, the method, static_add_one , in the two classes do not require the instance of the class(self) in calculation.

The method static_add_one in the class test1 is decorated by @staticmethod and work properly.

But at the same time, the method static_add_one in the class test2 which has no @staticmethod decoration also works properly by using a trick that provides a self in the argument but doesn't use it at all.

So what is the benefit of using @staticmethod? Does it improve the performance? Or is it just due to the zen of python which states that "Explicit is better than implicit"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason to use staticmethod is if you have something that could be written as a standalone function (not part of any class), but you want to keep it within the class because it's somehow semantically related to the class. (For instance, it could be a function that doesn't require any information from the class, but whose behavior is specific to the class, so that subclasses might want to override it.) In many cases, it could make just as much sense to write something as a standalone function instead of a staticmethod.

Your example isn't really the same. A key difference is that, even though you don't use self, you still need an instance to call static_add_one --- you can't call it directly on the class with test2.static_add_one(1). So there is a genuine difference in bejavior there. The most serious "rival" to a staticmethod isn't a regular method that ignores self, but a standalone function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...