Why does pycharm propose to change method to static

前端 未结 9 1520
面向向阳花
面向向阳花 2020-12-22 18:41

The new pycharm release (3.1.3 community edition) proposes to convert the methods that don\'t work with the current object\'s state to static.

相关标签:
9条回答
  • 2020-12-22 18:59

    I agree with the answers given here (method does not use self and therefore could be decorated with @staticmethod).

    I'd like to add that you maybe want to move the method to a top-level function instead of a static method inside a class. For details see this question and the accepted answer: python - should I use static methods or top-level functions

    Moving the method to a top-level function will fix the PyCharm warning, too.

    0 讨论(0)
  • 2020-12-22 19:00

    PyCharm "thinks" that you might have wanted to have a static method, but you forgot to declare it to be static (using the @staticmethod decorator).

    PyCharm proposes this because the method does not use self in its body and hence does not actually change the class instance. Hence the method could be static, i.e. callable without passing a class instance or without even having created a class instance.

    0 讨论(0)
  • 2020-12-22 19:06

    This error message just helped me a bunch, as I hadn't realized that I'd accidentally written my function using my testing example player

    my_player.attributes[item] 
    

    instead of the correct way

    self.attributes[item]
    
    0 讨论(0)
提交回复
热议问题