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“?

5

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 behavior there. The most serious “rival” to a staticmethod isn’t a regular method that ignores self, but a standalone function.

4

Today I suddenly find a benefit of using @staticmethod.

If you created a staticmethod within a class, you don’t need to create an instance of the class before using the staticmethod.

For example,

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!!!!!!!!!!!!!!!!!!!!

Since the method parse is strongly related to the classes File1 and File2, it is more natural to put it inside the class. However, sometimes this parse method may also be used in other classes under some circumstances. If you want to do so using File1, you must create an instance of File1 before calling the method parse. While using staticmethod in the class File2, you may directly call the method by using the syntax File2.parse.

This makes your works more convenient and natural.

2

I will add something other answers didn’t mention. It’s not only a matter of modularity, of putting something next to other logically related parts. It’s also that the method could be non-static at other point of the hierarchy (i.e. in a subclass or superclass) and thus participate in polymorphism (type based dispatching). So if you put that function outside the class you will be precluding subclasses from effectively overriding it. Now, say you realize you don’t need self in function C.f of class C, you have three two options:

  1. Put it outside the class. But we just decided against this.

  2. Do nothing new: while unused, still keep the self parameter.

  3. Declare you are not using the self parameter, while still letting other C methods to call f as self.f, which is required if you wish to keep open the possibility of further overrides of f that do depend on some instance state.

Option 2 demands less conceptual baggage (you already have to know about self and methods-as-bound-functions, because it’s the more general case). But you still may prefer to be explicit about self not being using (and the interpreter could even reward you with some optimization, not having to partially apply a function to self). In that case, you pick option 3 and add @staticmethod on top of your function.

Use @staticmethod for methods that don’t need to operate on a specific object, but that you still want located in the scope of the class (as opposed to module scope).

Your example in test2.static_add_one wastes its time passing an unused self parameter, but otherwise works the same as test1.static_add_one. Note that this extraneous parameter can’t be optimized away.

One example I can think of is in a Django project I have, where a model class represents a database table, and an object of that class represents a record. There are some functions used by the class that are stand-alone and do not need an object to operate on, for example a function that converts a title into a “slug”, which is a representation of the title that follows the character set limits imposed by URL syntax. The function that converts a title to a slug is declared as a staticmethod precisely to strongly associate it with the class that uses it.

 Explicit is better than implicit?

On the contrary, the decorator allows for calling this function as if it were a normal class method. So when reading the calling code, the fact that it is actually a static method is obscured.

The reason why you would use this function is probably exactly because developers do not have to bother with whether to include or omit “self”. This saves changing the calling code after a static method needs to become a class method.

class Test:

    @staticmethod
    def method():
        print('base')


class Derived(Test):

    def method(self):
        print('derived')


t = Test()
t.method()         # Success, but would fail without decorator
Test.method()      # Success, with or without decorator

d = Derived()
d.method()         # Success with or without decorator
Derived.method()   # Always fails, this is no longer a static method

I think you hit it on the head here:

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.

As you said, @staticmethod provides the self parameter implicitly so that you can call the method from an instance instead of the class and not have to explicitly write the self parameter. Per https://docs.python.org/3/library/functions.html#staticmethod:

A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()).

For C().f() to work, you either need to decorate f() with @staticmethod (or explicitly call staticmethod()) or explicitly add the self parameter as you have done in your example.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật