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()
'Python tips' 카테고리의 다른 글
datetime UTC +9 한국 시간 (0) | 2024.06.19 |
---|---|
임시 비밀번호, 랜덤 문자열 generator (0) | 2024.05.08 |
map(), filter(), pipe()를 활용하여 데이터 다루기 (0) | 2024.04.08 |
Pydantic을 활용한 JSON, dict 다루기 (0) | 2024.04.01 |
python-dotenv, pydantic_settings를 통한 환경 변수 관리 (0) | 2024.03.28 |