1. str
# add_string_by_plus 주소가 계속 바뀜
add_string_by_plus = ""
for i in range(50):
add_string_by_plus += str(i)
print(add_string_by_plus)
---------------------------------
#좀더 최적화된 방식
import io
add_string_by_plus = io.StringIO()
for i in range(50):
add_string_by_plus.write(str(i))
string_by_plus = add_string_by_plus.getvalue()
print(string_by_plus)
2. try catch와 contextlib.suppress
filename = "타겟.jpg"
try:
os.remove(filename)
except FileNotFoundError:
print('에러입니다.')
---------------------------
filename = "타겟.jpg"
#FileNotFoundError가 아니라면 아래 코드를 실행하라는 뜻
with contextlib.suppress(FileNotFoundError):
os.remove(filename)
3. 파이썬 정수와 is / ==
a = 256
b = 256
print(a == b) # True, 값이 같기 때문에 True를 반환 (동등성을 비교)
print(a is b) # True, 파이썬에서는 작은 정수(-5 ~ 256) 객체는 동일성을 유지함 (성능최적화를 위해 캐싱 사용)
# 쉽게 말해 a와 b의 주소가 같음. 캐시에 저장된 256이라는 주소를 a와 b가 가진것.
#같은 값인지, 같은 객체인지(메모리 주소) 확인
c = 256
print(b is c)
print(id(a)) # a의 메모리 주소 출력
print(id(b)) # b의 메모리 주소 출력
print(id(c)) # c의 메모리 주소 출력
a = 257
b = 257
print(a == b) # True, 값이 같기 때문에 True를 반환
print(a is b) # False, 257 이상의 정수는 다른 객체로 취급될 수 있음
자바스크립트의
== / === 차이점과 유사
4. 바다코끼리 연산자 (Assignment Expressions, 대입표현식) -> 전역변수 선언하기 귀찮다면
numbers = [1, 2, 3, 4, 5]
# 일반적인 방식
length = len(numbers)
print(length) # 5
# Walrus operator를 사용하여 간결하게 처리가능
print((length := len(numbers))) # 5
print(length)
5. 큰 수에 대해 언더바를 넣어도 없는 것처럼 처리
big_number = 1_234_000_000_000_000
print(big_number) # 1234000000000000
6. 장고(Django)에서 DB로부터 객체를 불러올 때
# 모든 사용자 객체를 가져온다.
users = User.objects.all() # DB Hit 1
for user in users:
# 추가적인 쿼리 예: 사용자의 프로필을 가져오는 쿼리
profile = user.profile # `user.profile` 접근 시 유저 숫자만큼 쿼리가 실행될 수 있음 DB Hit N
print(profile)
#개선
users = User.objects.select_related('profile').all() #여기서 데이터베이스 조회 1회만 실행 DB Hit 1
# 위 조회된 내용을 바탕으로 데이터를 꺼내서 print
for user in users:
print(user.profile)
'파이썬' 카테고리의 다른 글
python에서 json파일을 읽을 때 '한글' 도 읽는 방법 (1) | 2024.09.25 |
---|---|
property 데코레이터 (0) | 2024.09.10 |
파이썬에서의 모듈러 연산(음의 정수) (0) | 2024.08.02 |
reverse iterator등의 Iterator 유의점 (0) | 2024.07.17 |
AI 웹 개발 공부 3일 차 (사전 캠프) (0) | 2024.05.31 |