본문 바로가기
언어 정리/python 개념이해,문법정리

validation check ( isinstance , hasattr , try except raise )

by 알 수 없는 사용자 2022. 7. 14.

isinstance

type 형이 의도한게 맞는지 확인함

isinstance(1, int)
# 1이 int형인지 알아봅니다. 결과는 True 입니다. 

isinstance(1.2, float)
# 1.2가 float형인지 알아봅니다. 결과는 True 입니다. 

isinstance(1.2, int)
# 1.2가 int형인지 알아봅니다. 결과는 False입니다. 

isinstance("hi", str)
"hi"가 스트링인지 알아봅니다. 결과는 True입니다.

isinstance(mylist, list)
# mylist가 list형인지 알아봅니다. 결과는 True입니다.

my_conf = {
    'version': 1,

    'info': {
        'conf_one': 2.5,
        'conf_two': 'foo',
        'conf_three': False,
        'optional_conf': 'bar'
    }
}
print(isinstance(my_conf,dict))
# myconf가 dict형인지 알아봅니다 결과는 True 입니다.

simclass = CSimple()
isinstance(simclass, CSimple)
# simclass가 CSimple 클래스인지 확인합니다. 결과는 True입니다.

hasattr

해당 클래스에 해당 멤버변수가 있는지 확인

hasattr( 해당클래스, '해당멤버변수' )

ex)

class sample:
    def __init__(self):
        self.a = 1
        self.b = 2

    def test(self):
        pass


obj_1 = sample()
print(hasattr(obj_1,'a'))
print(hasattr(obj_1,'b'))
print(hasattr(obj_1,'self.a'))


try except raise

형태로 설명

1.

try :

    ~~~~

except :

    pass

 

2.  에러 뜨는 데 무슨 에러일지 잘 모를 때

try :

    ~~~~

except Exception as e:

    print(e)

 

3.

try :

    ~~~~

except ValueError:

    print("올바른 value 입력 필요")

 

4.

try :

    ~~~~

except ValueError:

    raise ValueError( "밸류에러뜸용" )

 

5.

try :

    ~~~~

except ValueError:

    print("val err")

except Exception as e:

    raise e 

else:

    break

finally:

    print("마무으리")

 

 

-----------

error 종류 ( 주로나는)

ValueError

TypeError

DecodeError ( json 파일 변환 할 때 )


 

 

 

 

 

 

 

 

 

 

 

 

 

댓글