반응형
Python에서 class를 자주 사용할때, 초기 입력되는 파라미터를 체크하는데 방법으로는 아래 방법을 사용하면 좋을 듯하다.
첫번째는 raise 를 통해 예외 상황을 전달하는 것이다. 가장 많이 사용될 방법으로 이를 위해서는 try/except를 사용해야 한다. 예제 코드는 아래와 같다.
class Address(object):
def __init__(self, city, contry):
if not (city and contry):
raise ValueError('Empty value not allowed')
self.city, self.contry = city, contry
try:
addr = Address(city, contry)
except ValueError:
# 입력 없음 오류 발생
else:
# 원하는 코드 수행
두번째 방법은 @classmethod를 사용할 수 있다. @classmethod는 class를 생성하지 않은 상태에서 사용할 수 있기 때문에 생성 시점에 바로 사용할 수 있다.
아래와 같이 값이 없다면, None를 결과값을 전달함으로써, 현재 문제가 있음을 알 수 있다.
class Address(object):
def __init__(self, city, contry):
self.city, self.contry = city, contry
@classmethod
def create_valid_address(cls, city, contry):
if not (city and contry):
return None
return cls(city, contry)
addr = Address.create_valid_address(city, contry)
if addr is not None:
# ...
'Python' 카테고리의 다른 글
Python 인증서 오류 해결 - SSLError SSLCertVerificationError CERTIFICATE_VERIFY_FAILED (0) | 2022.07.29 |
---|---|
Python - FastApi Cross-Origin Resource Sharing (CORS) 이해/해결 (0) | 2022.07.25 |
Python - 리스트에서 같은 아이템 찾기 List equal item check any/all (0) | 2022.07.20 |
Python - 지능형 리스트(List Comprehension) 이해 (0) | 2022.07.15 |
Python - 자주 사용되는 IP, SHA256, SHA1, MD5, URL - Regex 패턴 (0) | 2022.07.14 |
댓글0