Python
python static method, class method
원펀만
2020. 6. 8. 00:19
공통점
static method, class method는 둘 다 정적 메서드이다
둘 다 인스턴스를 생성하지 않고 class의 메서드를 바로 실행할 수 있다는 것이다.
인스턴스 없이 클래스의 속성에 접근할 수 있게 해준다.
차이점
class method 사용 시 cls 인자가 추가된다.
cls란?
클래스를 가리킴. 클래스의 속성에 접근할 수 있게 해줌.
@staticmethod
class hello:
num = 10
#@staticmethod
def calc(x):
return x + hello.num
print(hello.calc(10))
class hello:
num = 10
@staticmethod
def calc(x):
return x + hello.num
print(hello.calc(10))
# result 20
class hello2:
num = 10
@staticmethod
def calc2(x):
return x + hello.num
class hello3(hello2):
hello2.num = 0 # 부모 클래스 속성 변경 불가
print(hello3.calc2(10))
# result 20
@classmethod 는 클래스의 속성을 바꾸는 용도로 사용할 수 있음
class greeting:
text = "say something"
@classmethod
def say(cls):
return cls.text
class hi(greeting):
text = "hi"
print(hi.say())
# result hi
##########################
class greeting2:
text = "say something"
@classmethod
def say2(cls):
return cls.text
class hi2(greeting):
#text = "hi"
pass
print(hi2.say())
# resykt say something
cls는 상속 받은 클래스에서 먼저 속성을 찾는다. 상속 받은 클래스에서 속성 변경이 없는 경우 부모 클래스의 속성을 찾는다.