1 개요[ | ]
- python @classmethod, @staticmethod
- 파이썬에서 @classmethod와 @staticmethod 차이점을 알아보자.
- 각 차이점을 이해하기 위해 클래스 이름을 얻는 메소드를 Instance Method, Class Method, Static Method 의 형태로 각각 구현해 보자.
2 일반 메소드 (InstanceMethod)[ | ]
Python
Copy
class InstanceMethod(object):
def __init__(self):
pass
def get_class_name(self):
return self.__class__.__name__
IM = InstanceMethod()
print(IM.get_class_name())
- → 인스턴스 IM 생성후, 생성된 인스턴스 IM으로 get_class_name 메소드 호출
3 @classmethod[ | ]
- 클래스 메소드는 일반 메소드와 달리 인스턴스 생성없이 곧장 클래스를 통한 메소드 호출이 가능하다.
- 일반 메소드가
self
를 넘기는 것처럼 클래스인cls
를 넘겨준다. - 인스턴스의 생성을 통해서도 메소드 호출이 가능하다.
Python
CPU
0.0s
MEM
8M
0.0s
Copy
class ClassMethod(object):
def __init__(self):
pass
@classmethod
def get_class_name(cls):
return cls.__name__
print(ClassMethod.get_class_name())
ClassMethod
4 @staticmethod[ | ]
- 스태틱 메소드는 인스턴스 없이 호출이 가능하다는 점에서 @classmethod와 동일하나
cls
를 넘겨주지 않아도 된다는 점에서는 차이가 있다. - 인스턴스의 생성을 통해서도 메소드 호출이 가능하다.
Python
CPU
0.0s
MEM
8M
0.0s
Copy
class StaticMethod(object):
classname = 'StaticMethod'
def __init__(self):
pass
@staticmethod
def get_class_name():
return StaticMethod.classname
print(StaticMethod.get_class_name())
StaticMethod
5 같이 보기[ | ]
편집자 John Jeong Jmnote bot Jmnote
로그인하시면 댓글을 쓸 수 있습니다.
- 분류 댓글:
- Python (25)
리눅스 Python 2.7 컴파일 설치 ― …리눅스 Python 2.7 컴파일 설치 ― …리눅스 Python 2.7 컴파일 설치 ― …리눅스 Python 2.7 컴파일 설치 ― …리눅스 Python 2.7 컴파일 설치 ― Jmnote리눅스 Python 2.7 컴파일 설치 ― ㅇㅇㅇ미운코딩새끼 ― 승호 도령미운코딩새끼 ― 불탄고등어미운코딩새끼 ― 김레이미운코딩새끼 ― 호박이미운코딩새끼 ― Junhg0211미운코딩새끼 ― 김왼손미운코딩새끼 ― 용딘이미운코딩새끼 ―Pinkcrimson
유기농냠냠파이썬 ― 호박유기농냠냠파이썬 ― 이에스유기농냠냠파이썬 ― 이승현파이썬 global ― Jmnote파이썬 global ― John Jeong파이썬 global ― Jmnote파이썬 global ― John Jeong파이썬 global ― John Jeong파이썬 global ― John Jeong파이썬 global ― Jmnote파이썬 global ― John Jeong