파이썬 내장함수
코딩을 하다 보니 파이썬 내장 함수를 몰라서 비효율적으로 코딩하는 경우가 종종 발생했다. 내장 함수에 대해 remind 하기 위해 작성
abs : 절댓값 반환
abs(-13)
>> 13
all : iterable의 모든 요소가 참이면 True
lst = [True,True,False]
all(lst)
>> False
lst_2 = [True,True,True]
all(lst_2)
>> True
lst_3 = []
all(lst_3)
>> True
비어있는 경우도 True가 나온다.
any : iterable 중 하나라도 참이면 True
lst_1 = [True,True,False]
any(lst_1)
>> True
lst_2 = [False,False,False]
any(lst_2)
>> False
lst_3 = []
any(lst_3)
>> False
비어있는 경우는 False가 나온다.
ascii : ascii코드로 변환
ascii("가나다")
>> "'\\uac00\\ub098\\ub2e4'"
ascii("abc")
>> "'abc'"
bin : 이진수로 변환, 파이썬에서는 "0b"가 앞에 붙는다.
bin(17)
>> '0b10001'
bin(-17)
>> '-0b10001'
bool : 참,거짓을 판단해서 True, False 반환
my_input = []
bool(my_input)
>> False
my_input = [0]
bool(my_input)
>> True
my_input = False
bool(my_input)
>> False
my_input = None
bool(my_input)
>> False
breakpoint : 디버거 진입(3.7 버전 이상) import pbd ; pbd.set_trace()와 동일하다.
breakpoint()
callable : callable 한지 판단해서 True,False 반환
def myfunction():
print("!")
callable(myfunction)
>> True
class MyClass:
def __init__(self):
pass
check_MyClass = MyClass()
callable(check_MyClass)
>> False
class MyClassCall:
def __init__(self):
pass
def __call__(self):
pass
check_MyClassCall = MyClassCall()
callable(check_MyClassCall)
>> True
divmod : 몫과 나머지
divmod(13,5)
>> (2,3)
eval : 문자열을 받고 실행
eval("1+1")
>> 2
eval('"abc" + "def"')
>> 'abcdef'
"rm rf" 같은 문자열이 들어가면 실제로 실행됨.. 조심할 필요 있음
비슷한 함수로 ast.literal_eval이 있음
format : str(value)
text = "text1 : {}, text2 : {}".format("가나다","ABC")
print(text)
>> text1 : 가나다, text2 : ABC
frozenset : set인데 수정 불가
myset = set([1,2,3])
myset.update([4])
print(myset)
>> {1,2,3,4}
myfset = frozenset([1,2,3])
myfset.update([4])
>> AttributeError: 'frozenset' object has no attribute 'update'
getattr : 주어진 이름의 attribute값 반환 / delattr : attribute 삭제 / hasattr : attribute값 있으면 True, 없으면 False
class MyClass:
def __init__(self):
self.item1 = "first"
self.item2 = "second"
myclass = MyClass()
getattr(myclass,"item1")
>> "first"
getattr(myclass,"item2")
>> "second"
myclass.item1
>> "first"
myclass.item2
>> "second"
delattr(myclass,"item1")
myclass.item1
>> AttributeError: 'MyClass' object has no attribute 'item1'
hasattr(myclass,"item1")
>> False
hasattr(myclass,"item2")
>> True
hash : 객체의 hash value값을 가져온다.
text = "my text"
hash_value = hash(text)
>> -3503068283177001803
https://yunaaaas.tistory.com/46
[Python 자료구조] Hash(해시)
파이썬에서 해시(Hash)는 어떻게 구현할 수 있을까요!? 파이썬에서는 Dictionary 라는 자료구조를 통해 해시를 제공합니다. 그리고 Dictionary는 dict클래스에 구현되어있습니다! 해시 언제 사용하면 좋
yunaaaas.tistory.com
id : 객체 고유값 반환
파이썬 id 함수 : 객체 고유값을 알아오기 위해 쓴다.
파이썬에는 built in 함수로 id가 있습니다. 문서에 따르면, 이것은 객체의 고유값을 리턴하는 메서드입니다. cpython은 주솟값을 돌려준다고 문서에 언급이 되어 있습니다. 저는 이 메서드를 어떤
codingdog.tistory.com
isinstance : 객체의 타입, 클래스 등을 확인하여 True, False 반환
isinstance("my text", str)
>> True
isinstance("my text", int)
>> False
class MyClass:
def __init__(self):
pass
myclass = MyClass()
isinstance(myclass,MyClass)
>> True
issubclass : subclass이면 True 반환
class MyClass:
def __init__(self):
pass
class MySubClass(MyClass):
pass
issubclass(MySubClass,MyClass)
>> True
iter : iterator 객체로 변환
mytext = "my text"
type(mytext)
>> str
type(iter(mytext))
>> str_iterator
property : 메서드에 @property 데코레이터를 붙여 getter/setter 기능 수행
## 출처 : https://dojang.io/mod/page/view.php?id=2476
class Person:
def __init__(self):
self.__age = 0
@property
def age(self): # getter
return self.__age
@age.setter
def age(self, value): # setter
self.__age = value
james = Person()
james.age = 20 # 인스턴스.속성 형식으로 접근하여 값 저장
print(james.age) # 인스턴스.속성 형식으로 값을 가져옴
hash에 대해서는 더 깊은 공부가 필요해 보인다.