in python,what is the difference below, and which is better

This question already has an answer here:

  • What is the difference between @staticmethod and @classmethod in Python? 24 answers

  • If both are working it means that inside make_attr you are not using self .

    Making it a regular non-static method only makes sense if the code could logically depend on the instance and only incidentally doesn't depend on it in the current implementation (but for example it could depend on the instance in a class derived from this class).


    When it comes to functionality, @staticmethod doesn't really matter. It's value is semantic - you are telling yourself, or other coders, that even though this function belongs to the namespace of the class, it isn't tied to any specific instance. This kind of tagging can be very useful when refactoring the code or when looking for bugs.


    In either, attr is a local variable and does not depend on anything in the class. The results are the same. Marking it as static gives you the benefit of knowing this, and being able to access it directly, such as Demo2._make_attr() without having to create and instance of the class.

    If you want it to acces the class variable, you would reference it as self.attr . But if you're doing this, then Demo2._make_attr() can no longer be static.

    链接地址: http://www.djcxy.com/p/9174.html

    上一篇: classmethod在这段代码中做了什么?

    下一篇: 在python中,下面有什么区别,哪个更好