Python Camp

Logo

Life is short. You need Python.

Introducing Python Object Types


The Python Conceptual Hierarchy

Python Object

Python’s Core Data Types

Built-in object preview

# a literal expression that generates and returns a new string object
'spam'

assignment vs. rebinding

# [Error] 'obj'라는 변수는 정의(선언)되지 않았으므로 사용할 수 없다.
obj
# Print all interactive variables, with some minimal formatting.
%who
# Return a sorted list of all interactive variables.
%who_ls
# Like %who, but gives some extra information about each variable.
%whos
# 1. 'obj' is a string object.
obj = 'spam'

# 자동으로
type(obj)
len(obj)
# 2. 'obj' is a list object.
obj = [1, 2, 3]

type(obj)
len(obj)
# 3. Now, 'obj' is a numeric (integer) object.
obj = 10

type(obj)
# [Error] int object에는 len function을 사용할 수 없다. (또는 int object는 len method를 가지고 있지 않다.) 
len(obj)

Numbers


Numeric Objects

Numeric objects를 통해서 다시 한 번 binding 과정을 살펴봅시다. Assignment operator를 통해 값을 할당할 수 있습니다.

x = 1

x

Assignment operator를 수학 기호인 등호와 혼동하면 안 됩니다.

# '1 = 1 + 10'이라니?
x = x + 10

x

float type and numeric operation

x = 1.1
y = 2.2
z = 3.3

# Why?
z == x + y

The other numeric objects in third-party libraries (e.g. matrixes and vectors)

from decimal import Decimal

a = Decimal('.2')
b = Decimal('.1')
c = a + b

c

Strings


type('A')
type('Hello, world!')
type("Apple")

Q. 문자열 안에 ‘ 또는 “를 포함시키고 싶다면?

# TODO:
s = '''Hello,
world
and
Python!'''

s
s = """Hello,
world
and
Python!"""

s
print(s)
s = '이렇게도 줄바꿈이 가능하지만, \
연결만 해줄 뿐 \
실제로 개행이 들어가지는 않는다.'

s
print(s)

Escape Code

\n는 갑자기 어디서 튀어나온 건가요?

# TODO: 점프 투 파이썬 참조

String Prefix

b = b'It is not the str type but the bytes type.'

type(b)
b
r = r'Backslash(\)를 literal character로 다룸으로써 \n, \t 등 escape characters를 허용하지 않는다.'

r
print(r)
a = 1
b = ': it is a expression evaluated at run time.'
f = f'a is {a}{b}'

f

String Formatting

# TODO: 점프 투 파이썬 참조

Sequence

Length of sequence

s = 'Hello, Python!'

len(s)

Indexing

# Positive index
s[0]
# Negative index
s[-1]

Q. 숫자만 index로 사용할 수 있을까?

# TODO:

Slicing

# 세미콜론 뒤에 위치하는 index의 의미에 주의!
s[7:13]

Q. 위와 동일한 결과를 만드는 slicing 방법?

# TODO:
s[7:]
s[:7]
s[:]

자유롭게 indexing과 slicing 연습을 하다보면 문득 궁긍해질 것이다. 기존 object ‘s’는 어떻게 되었을까?

# 's'는 변하지 않았다. Indexing과 slicing이 return(반환)하는 것은 새로운 object이기 때문이다.
s

Polymorphism

# Plus sign (+) means addition for numbers.
1 + 1
# Plus sign (+) means concatenation for string.
'Hello, ' + 'Python!'

Mutability

Immutable objects cannot be changed in place after they are created.

s
# [Error] String은 immutable이므로 값을 직접 변경할 수 없다.
s[0] = 'h'

Q. 그렇다면, 첫 글자 H를 소문자로 변경하기 위해 어떻게 해야 할까?

# TODO:

Type-Specific Methods

built-in functions: The Python interpreter has a number of functions and types built into it that are always available.

s
s.find('ll')
s.replace('Hello', 'hello')

Q. replace method를 사용했는데도 ‘s’는 변하지 않았다. 왜 그럴까?

s

Q. str에 속하는 methods는 어떤 것들이 있는지 확인해보자. ‘r’로 시작하는 methods는 몇 개일까?

# TODO:

Q. 다음 코드는 어떻게 해석해야 할까?

s.upper().split(',')

Formatting

Getting Help


dir

Q. dir을 알았으니 이제 우리는 str에 속한 모든 attributes와 methods(function attributes)의 개수를 알 수 있다. 총 몇 개일까?

# TODO:

Built-in functions의 개수와 각각의 이름도 알 수 있다.

len(dir(__builtin__))
dir(__builtin__)

Help

help()
help(str)
help(s)
help('literal')
help(str.lower)
# Shitf + Tab: cell을 실행하지 않고 바로 Docstring 보기
# Shitf + Tab을 연속으로 두 번 누르면 스크롤이 생성되면서 Docstring 전체를 볼 수 있다.
s.lower()
# Introduction and overview of IPython's features
?

# Details about 'object'.
str?

# More detailed, verbose information about 'object'.
sys??

Lists


l = [1, 'item in list', [10, 10., 0o10, 0x10]]

l
id(l)
l.append('new item')

l
id(l)
l[0] = 817

l
id(l)

Q. Sequence operations를 사용해보자.

# TODO:

Q. Type-specific operations를 사용해보자.

# TODO:

Bounds Checking

l
# [Error] 범위를 벗어난 위치에 대해 indexing 할 수 없다.
l[100]
# [Error] 범위를 벗어난 위치에 값을 할당할 수 없다.
l[100] = 42

Nesting

# a 3 × 3 matrix, as nested lists
list_with_nested_lists = [[1, 2, 3],
                          [4, 5, 6],
                          [7, 8, 9]]

list_with_nested_lists

Q. list_with_nested_lists의 길이는?

# TODO:

Q. Indexing을 어떻게 해야 할까. 먼저 두 번째 row [4, 5, 6]을 가져온 후, 세 번째 item 6만 가져와보자.

# TODO:

Comprehensions

list_with_nested_lists = [[1, 2, 3],
                          [4, 5, 6],
                          [7, 8, 9]]
col_list = [row[1] for row in list_with_nested_lists]

col_list
col_list = [row[1] + 1 for row in list_with_nested_lists]

col_list
col_list = [row[1] for row in list_with_nested_lists if row[1] > 3]

col_list

Dictionaries


d = {'이름': '김태진', '학교': '가천대', '학년': 4, '수강과목': ['의료영상', '생체신호처리']}
d = {'name': 'Taejin Kim', 'university': 'Gachon Univ.', 'grade': 3, 'lectures': ['Medical Imaging', 'Biosignal Processing']}

d

We can index dictionary by key to fetch and change the keys’ associated values.

# Fetch
d['name']
# Change
d['grade'] = 4

d

Unlike out-of-bounds assignments in lists, which are forbidden, assignments to new dictionary keys create those keys.

# An empty dictionary
d = {}

d
# Add a new key and the keys' associated value.
d['name'] = 'Taejin Kim'

d
d['university'] = 'Gachon Univ.'
d['grade'] = 4
d['lectures'] = ['Medical Imaging', 'Biosignal Processing']

d

Nesting

d['name'] = {'first': 'Taejin', 'last': 'Kim'}

d

Q. Indexing dictionary by key로 first name 가져오기.

# TODO:

Q. 수강과목 추가하기.

# TODO:

Q. 마지막으로 추가한 수강과목 indexing 하기.

# TODO:

Missing Keys

# [Error] 'age'란 Key는 존재하지 않는다. Referencing a nonexistent key is an error.
d['age']
d.items()
d.keys()
d.values()

in: membership expression

1 in [1, 2, 3]
't' in 'Python'
'th' in 'Python'
1.0 in [1, 2, 3]
'p' in 'Python'
'age' in d

if statement: the main selection statement tool in Python

if 'age' in d:
    d['age']
d.get('age')
# Key가 존재하지 않을 경우 반환되는 default 값은 None
print(d.get('age'))
# Key가 존재하지 않을 경우 반환되는 값을 0(get method에 전달되는 두 번째 argument(인자))으로 지정
d.get('age', 0)

사실 get method는 if/else ternary expression(an if statement squeezed onto a single line)으로 정의되어 있다.

d['age'] if 'age' in d else 0

Iteration and Optimization

iterable

iterable_vs_iterator

Q. 아니 그런데, 코딩만 잘 하면 되지 이런 걸 꼭 알아야 해요?

# TODO: 빈 list 생성
list()
# TODO: list의 소괄호 안에 커서를 두고 Shitf + Tab을 눌러보자!
list(d.keys())

Tuples


Q. lsit와 매우 비슷해보인다! 그리고 이제 우리는 sequence와 immutable이 무엇인지 안다! 그렇다면, tuple로 무엇을 할 수 있을지 추론해보자.

# TODO:

다음과 같이 한 개의 아이템을 갖는 튜플을 만들 때 주의!

t = (1)

type(t)
t
t = (1,)

type(t)
t
t = (1, 2, 3)

# [Error] Tuples are immutable sequences.
t[0] = 0
# [Error] Tuples don't grow and shrink.
t.append(4)

Tuple Packing

d = 1, 2, 3, 4, 5

type(d)
d

Sequence Unpacking

a, b, c = 1, 2, 3
# a, b, c = 1, 2, (3, )
# a, b, c = 1, 2, [3, 4]
type(a)
type(b)
type(c)
# [Error] 할당 연산자 왼쪽의 식별자 개수와 오른쪽의 값(요소) 개수가 같지 않은 경우
a, b, c = 1, 2
# [Error] 할당 연산자 왼쪽의 식별자 개수와 오른쪽의 값(요소) 개수가 같지 않은 경우
a, b, c = 1, 2, 3, 4

*을 사용하면 유동적인 packing, unpacking이 가능하다.

# 첫 요소만 a에 pack, 나머지 전부를 b에 pack
a, *b = 1, 2, 3, 4, 5
a
b
# 마지막 요소만 b에 pack, 나머지 전부를 a에 pack
*a, b = 1, 2, 3, 4, 5
a
b
# 첫 요소를 a에, 마지막 요소를 c에, 나머지 전부를 b에 pack
a, *b, c = 1, 2, 3, 4, 5
a
b
c

C에서는 temp 변수 만들어서 해야 했던 swapping arguments가 Python에서는 이렇게 간단하다.

a = 5
b = 10

"""
temp = a
a = b
b = temp
"""

a, b = b, a
a
b

Files


컴퓨터는 영원히, 제약 없이 모든 변수의 값을 기억할 수 있을까? 메모리상의 정보는 커널 또는 컴퓨터를 재시작하면 삭제되어 재사용할 수 없다. 따라서 파일로 저장해야 정보를 보존할 수 있다.

# Write a file.
f = open('test.txt', 'w')
f.write('Hello\n')
f.write('word\n')
f.close()
# Read a file.
f = open('test.txt', 'r')
text = f.read()
f.close()

text

Two ways to print every object in Python

text
print(text.__repr__())
print(text)
print(text.__str__())

Other Core Types


l = [1, 2, 3, 4, 5, 4, 3, 2, 1, 1, 1]

l
set(l)
{n ** 2 for n in [1, -1, 2, -2, 3, -3]}
placeholder = None

plc

Q. 초록색 코드, 넌 누구냐?

# TODO:

Type


l = [1, 2, 3]

print(type(l))
print(type(type(l)))

Type Testing

type(l) == type([])
type(l) == list
isinstance(l, list)

“Pythonic!”

pythonic_code

Again, everything in Python is an “object”.

Chapter Summary


To Home
To Lecture List