Nice programing

Python 클래스 정적 메서드

nicepro 2021. 1. 6. 20:49
반응형

Python 클래스 정적 메서드


이름 클래스 접두사로 호출 할 수있는 정적 메서드 만 포함하는 일종의 유틸리티 클래스를 만들고 싶습니다. 내가 뭔가 잘못하고있는 것 같습니다 :)

다음은 내 소규모 수업입니다.

class FileUtility():

    @staticmethod
    def GetFileSize(self, fullName):
        fileSize = os.path.getsize(fullName)
        return fileSize

    @staticmethod
    def GetFilePath(self, fullName):
        filePath = os.path.abspath(fullName)
        return filePath

이제 내 "주"방법 :

from FileUtility import *
def main():
        path = 'C:\config_file_list.txt'
        dir = FileUtility.GetFilePath(path)
        print dir

오류가 발생했습니다 : unbound method GetFilePath() must be called with FileUtility instance as first argument (got str instance instead).

여기에 몇 가지 질문이 있습니다.

  1. 내가 도대체 ​​뭘 잘못하고있는 겁니까? 정적 메서드를 클래스 이름으로 호출 할 수 없어야합니까?
  2. 정말 유틸리티 클래스가 필요합니까, 아니면 파이썬에서 동일한 것을 달성하는 다른 방법이 있습니까?
  3. main에서 코드를 변경하려고하면 다음과 같은 결과가 나타납니다. TypeError: GetFilePath() takes exactly 1 argument (2 given)

새로운 main:

from FileUtility import *
def main():
    objFile = FileUtility()
    path = 'H:\config_file_list.txt'
    dir = objFile.GetFilePath(path)
    print dir

self각 함수에서 인수를 취하기 때문에 오류가 발생 합니다. 정적이므로 필요하지 않습니다.

그러나이를 수행하는 'pythonic'방법은 정적 메서드로 가득 찬 클래스를 갖는 것이 아니라 모듈에서 자유 함수로 만드는 것입니다.

#fileutility.py:

def get_file_size(fullName):
    fileSize = os.path.getsize(fullName)
    return fileSize


def get_file_path(fullName):
    filePath = os.path.abspath(fullName)
    return filePath

이제 다른 파이썬 파일에서 (fileutility.py가 동일한 디렉토리 또는에 있다고 가정 PYTHONPATH)

import fileutility

fileutility.get_file_size("myfile.txt")
fileutility.get_file_path("that.txt")

정적 메서드를 구체적으로 언급하지는 않지만 다른 언어 인 PEP 8 에서 온 경우 파이썬 스타일 가이드는 파이썬 프로그래머가 생각하는 방법에 대한 좋은 읽기 및 소개입니다.


파이썬에서 정적 메서드를 만들면 안됩니다. 해야 할 일은 전역 함수 수준에 배치 한 다음 호출 할 때 해당 모듈에 액세스하는 것입니다.

foo.py :

def bar():
  return 42

baz.py :

import foo
print foo.bar()

정적 메서드는 첫 번째 매개 변수로 전달 된 개체를 가져 오지 않습니다 (개체 없음).

remove the self parameter and the calls should work. The import problem is relevant too. And the static comment relevant too.


In python, java-like (or whatever) static methods are not widely used as they don't really have a purpose.

Instead, you should simply define your "methods" as functions in a module:

#module1.py
def fun1():
    return do_stuff()
def fun2(arg):
    return do_stuff_with_arg(arg)

#main.py
import module1
if __name__ == '__main__':
    a = module1.fun()
    print module1.fun2(a)

Just remove self in methods definition. Your intention is to use as static. Self is to work with instance of that class.


If you want to use your functions defined in the class, you have just to create an instance of your class and apply the function.

So the result is :

dir = FileUtility().GetFilePath(path)

Just add () after your class name.

@staticmethod is not needed as you are using standard function, not static. But in your case the result is the same.


Just remove the self in the function definition. Since your using the static functions so you need not pass self as an argument for the functions. So your class and function should be like this:

class FileUtility():

    @staticmethod
    def GetFileSize(fullName):
        fileSize = os.path.getsize(fullName)
        return fileSize

    @staticmethod
    def GetFilePath(fullName):
        filePath = os.path.abspath(fullName)
        return filePath

ReferenceURL : https://stackoverflow.com/questions/12735392/python-class-static-methods

반응형