Python tips
@property와 __call__ 비교
tenjobs
2024. 5. 8. 14:17
class Calculate:
def __init__(self):
self.result = 3
@property
def one_plus_two(self) -> int:
"""
일급 객체와는 다르다.
일급 객체는 변수 할당, 함수 인자 전달, 함수의 리턴 값이 될 수 있는 특징이 있기 때문이다.
"""
return self.result
if __name__ == "__main__":
cal = Calculate()
print(cal) # <__main__.Calculate object at 메모리주소>
print(type(cal)) # <class '__main__.Calculate'>
# print(cal()) # 'Calculate' object is not callable 예외
print(cal.one_plus_two) # 3
print(type(cal.one_plus_two)) # int
if cal.one_plus_two == 3:
print("정답")
else:
print("오답")
- @property는 클래스 내에 구현된 메서드를 클래스의 속성(Attribute, Member)처럼 사용할 수 있다.
class Calculate:
def __init__(self):
self.result = 3
def __call__(self):
"""
인스턴스가 함수처럼 호출될 수 있다.
일급 객체다.
"""
return self.result
if __name__ == "__main__":
cal = Calculate()
print(cal) # <__main__.Calculate object at 메모리주소>
print(type(cal)) # <class '__main__.Calculate'>
print(cal()) # 3
print(type(cal())) # int
if cal() == 3:
print("정답")
else:
print("오답")
- 인스턴스를 callable 할 수 있다.
- 인스턴스 cal을 호출할 수 있다.
- cal()