IT story

pycharm이 메소드를 정적으로 변경하도록 제안하는 이유

hot-time 2020. 7. 5. 07:56
반응형

pycharm이 메소드를 정적으로 변경하도록 제안하는 이유


새로운 pycharm 릴리스 (3.1.3 커뮤니티 에디션)에서는 현재 객체의 상태에서 작동하지 않는 메소드를 정적으로 변환 할 것을 제안합니다.

여기에 이미지 설명을 입력하십시오

그 이유는 무엇입니까? 어떤 종류의 마이크로 성능 (또는 메모리) 최적화?


PyCharm 은 정적 메소드를 원했을 수도 있지만 " 정적 "이라고 선언하는 것을 잊어 버렸다고 생각합니다.

PyCharm은 메소드가 본문에서 사용 self 되지 않으므로 실제로 클래스 인스턴스를 변경 하지 않기 때문에이를 제안 합니다 . 따라서 메소드는 정적 일 수 있습니다. 즉, 이전에 클래스 인스턴스를 만들지 않고도 호출 할 수 있습니다.


@jolvi, @ArundasR 및 기타와 함께 경고를 사용하지 않는 멤버 함수에서 경고가 발생합니다 self.

PyCharm이 잘못되었다고 확신하는 경우 함수는이어야하며 @staticmethod경고가 0이 아닌 경우 다음 두 가지 방법으로 벗어날 수 있습니다.

해결 방법 # 1

def bar(self):
    self.is_not_used()
    doing_something_without_self()

def is_not_used(self):
    pass

해결 방법 # 2 [감사합니다 @ DavidPärsson ]

# noinspection PyMethodMayBeStatic
def bar(self):
    doing_something_without_self()

내가 가지고있는 응용 프로그램 (@staticmethod를 사용할 수없는 이유)은 프로토콜 하위 유형 필드에 응답하기위한 핸들러 함수 테이블을 만드는 것이 었습니다. 모든 핸들러는 동일한 형태의 코스 여야합니다 (정적 또는 비 정적). 그러나 일부는 인스턴스와 관련이 없었습니다. 그 정적을 만들면 "TypeError : 'staticmethod'개체를 호출 할 수 없습니다"라는 메시지가 나타납니다.

OP의 Consternation을 지원하면서 가능할 때마다 정적 메소드를 추가 할 것을 제안하고 나중에 코드를 더 제한적으로 만드는 것이 더 쉬운 것보다 더 쉽다 원칙에 위배됩니다. instance.f () 대신 class.f ()를 호출하십시오.

이 경고가 존재하는 이유를 추측합니다.

  • 그것은 StaticMethod를 보급합니다 . 개발자가 의도 한 것을 인식하게합니다.
  • @JohnWorrall이 지적했듯이, 실수로 기능이 빠져 있을 때주의를 기울 입니다.
  • 그것은 객체 모델을 다시 생각하게하는 신호입니다. 함수 가이 클래스에 전혀 속하지 않을 수도 있습니다.

이 경고의 이유는 Pycharm의 구성이라고 생각합니다. Editor-> Inspection에서 선택 사항 이 정적 일 수 있음을 선택 취소 할 수 있습니다.


클래스 메소드를 정적 메소드로 정의하면 다음과 같은 장점이 있습니다.

  • 클래스 이름을 사용하여 메소드를 호출 할 수 있으며 인스턴스화 할 필요가 없습니다.

남아있는 장점은 아마도 존재하지 않을 것입니다 :

  • 조금 더 빨리 달릴지도 모른다
  • 약간의 메모리를 절약

나는 여기에 주어진 대답에 동의합니다 (방법은 사용하지 않으므로 self장식 할 수 있습니다 @staticmethod).

클래스 내 정적 메서드 대신 최상위 함수로 메서드를 이동하고 싶을 수도 있습니다. 자세한 내용은이 질문과 허용되는 답변을 참조하십시오 : python-정적 메소드 또는 최상위 함수를 사용해야합니까

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


Since you didn't refer to self in the bar method body, PyCharm is asking if you might have wanted to make bar static. In other programming languages, like Java, there are obvious reasons for declaring a static method. In Python, the only real benefit to a static method (AFIK) is being able to call it without an instance of the class. However, if that's your only reason, you're probably better off going with a top-level function - as note here.

In short, I'm not one hundred percent sure why it's there. I'm guessing they'll probably remove it in an upcoming release.


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]

It might be a bit messy, but sometimes you just don't need to access self, but you would prefer to keep the method in the class and not make it static. Or you just want to avoid adding a bunch of unsightly decorators. Here are some potential workarounds for that situation.

If your method only has side effects and you don't care about what it returns:

def bar(self):
    doing_something_without_self()
    return self

If you do need the return value:

def bar(self):
    result = doing_something_without_self()
    if self:
        return result

Now your method is using self, and the warning goes away!

참고URL : https://stackoverflow.com/questions/23554872/why-does-pycharm-propose-to-change-method-to-static

반응형