[Python 기초 정리] 변수

서해빈·2021년 4월 17일
0

python

목록 보기
2/5

강의 바로가기

Variable

다양한 변수 선언법

변수 할당

다음의 경우 정수 객체 700가 생성되고, 변수 z, y, x가 차례대로 정수 객체를 참조하게 된다.

>>> x = y = z = 700
>>> print(id(x) == id(y) == id(z) == id(700))
True

cf) python도 string interning을 할까?

wiki에서는 string interning을 다음과 같이 설명하고 있다.

In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.

파이썬은 string이 immutable하다. 하지만 CPython에서는 대부분의 경우에 pool에서 string의 기존 존재 여부를 탐색하지 않는다. 다만 길이가 1인 string의 경우은 pool에서 참조한다.

>>> str(5) is str(5)
True
>>> str(50) is str(50)
False

integer의 경우 small integer pool과 large integer pool을 운용한다. small integer pool에는 [-5, 257) 범위의 정수를 미리 생성해두고, 나머지 정수는 필요시 large integer pool에 생성해 사용한다.

Object Identity

두 변수에 같은 정수 값을 할당할 때, 두 변수는 하나의 같은 정수 객체를 참조하게 된다.

>> m = 800
>> n = 800
>> print(m is n)
True

변수 네이밍 규칙

  • Camel Case: numberOfCollegeGraduates
  • Pascal Case: NumberOfCollegeGraduates
  • Snake Case: number_of_college_graduates

PEP8에 따르면 파이썬은 스네이크 케이스를 지향한다. class에서는 pascal case, 변수 및 함수에는 snake case를 사용하자.

예약어

  • False
  • def
  • if
  • raise
  • None
  • del
  • import
  • return
  • True
  • elif
  • in
  • try
  • and
  • else
  • is
  • while
  • as
  • except
  • lambda
  • with
  • assert
  • finally
  • nonlocal
  • yield
  • break
  • for
  • not
  • class
  • from
  • or
  • continue
  • global
  • pass

참고 및 참조

0개의 댓글