#pop
p_2 = arr_pop.pop()
print(arr_pop) #마지막 원소가 없어진 상태가 출력
print(p_2) #마지막 원소가 출력
#extend 리스트끼리 이어붙이기
list1.extend(list2)
#sort
arr.sort(reverse=True)
print(arr) # arr의 순서자체가 바뀜
#sorted
arr = [4, 3, 2.5, 7, 0.7, 9]
print(sorted(arr, reverse=True))
arr # 주어진 arr은 그대로 유지되어 있음
들여쓰기 : 코드블럭
for next로 iterator를 돌린다.
dir() : 어떤 변수와 메소드를 가지고 있는지 나열해줌, dir(list)
메타데이터 : 데이터에 대한 데이터
리스트가 효율적인 이유 : 메모리에 순차적으로 저장되기 때문
hash가능한 것들은 dictionary의 key값으로 설정가능
breakpoint() : 파이썬에서 디버깅에 사용
is는 변수가 같은 Object(객체)를 가리키면 True
==는 변수가 같은 Value(값)을 가지면 True
isinstance(object, class)는 첫 번째 인수로 인스턴스, 두 번째 인수로 클래스 이름을 받는다. 입력으로 받은 인스턴스가 그 클래스의 인스턴스인지를 판단하여 참이면 True, 거짓이면 False를 돌려준다.
assert는 뒤의 조건이 True가 아니면 AssertError를 발생한다.
문자열은 같은 값이라도 id가 같지않다.
인스턴스메소드 : self
클래스메소드
@ : 데코레이터
클래스에서 메서드를 통하여 속성의 값을 가져오거나 저장하는 경우가 있다. 이때 값을 가져오는 메서드를 getter, 값을 저장하는 메서드를 setter라고 부른다.
@property #getter
def name(self):
return self._name
@name.setter #settter
def name(self, a_name):
self._name = a_name
이런식으로도 따로 함수를 만들어 합치기도 가능.
age = property(get_age, set_age)
컨벤션으로 선언하게 되면 from module import * 를 했을때 _로 시작하는 것들은 모두 임포트에서 무시
getattr(), setattr() and delattr() : 속성불러오기, 속성set, 속성삭제
__dict__ : 속성과 값을 dict으로 보여줌
특정 예외가 발생했는지 검증하기 위해 assertRaises()를 호출
__str__ : 인스턴스 자체를 출력 할 때의 형식을 지정해주는 함수
repr 함수는 어떤 객체의 ‘출력될 수 있는 표현’(printable representation)을 문자열의 형태로 반환한다
isinstance(object, class )는 첫 번째 인수로 인스턴스, 두 번째 인수로 클래스 이름을 받는다.
super : 상속하는 클래스를 지정해줄 수 있다.
Ex.
import random
class Product:
def __init__(self, name, price=30, size=20, warmness=0.5, sweetness=0.5, identifier=random.randint(1000000,9999999)):
self.name = name
self.price=price
self.size=size
self.warmness=warmness
self.sweetness=sweetness
self.identifier=identifier
def sellability(self):
cal = self.size/self.price
if cal < 0.5:
return 'Not so sellable...'
elif cal >= 0.5 and cal < 1:
return 'Kinda sellable.'
else:
return 'Very sellable!'
def calory(self):
cal = self.size*self.sweetness
if cal < 10:
return '...it\'s light'
elif cal >= 10 and cal < 50:
return 'It\'s adequate.'
else:
return 'It\'s really heavy..!!'
class Tea(Product):
#만약 __init__ 메소드를 작성하지 않는다면 부모의 __init__을 실행함.
#def __init__이 Tea가 실행될때 작동하므로 알맞은 인수를 작성해줘야함.
#super()는 def __init__에서 받은 변수를 사용한다.
def __init__(self, name, price=30, size=10, warmness=0.5, sweetness=0.5, identifier=random.randint(1000000,9999999)):
super().__init__(name, price, size, warmness, sweetness, identifier)
def calory(self): #같은 이름의 메소드를 작성하면 대체됨.
return '...it\'s a tea. Only a few calories'
def drink(self):
warm = self.warmness
if warm < 0.5:
return 'it\'s too cold...'
elif warm >= 0.5 and warm < 1.0:
return 'Oh, it\'s warm!'
else:
return 'It\'s too hot!!'
self.fail('테스트 종료') 코드로 무조건 실패하도록
try except문 실행순서
sqlite로 연결
import sqlite3
conn = sqlite3.connect('test.db')
cur = conn.cursor()
cur.execute("""CREATE TABLE test_table (
name VARCHAR(32),
age INT);""")
cur.execute('SELECT * FROM test_table;').fetchall() #쿼리 결과 리스트 형태로 모두 조회
#fetchone() : 쿼리결과의 첫번째만 리턴
PostgreSQL로 연결
import psycopg2
conn = psycopg2.connect(
host="서버 호스트 주소",
database="데이터베이스 이름",
user="유저 이름",
password="유저 비밀번호")
위 두 경우의 차이점
connection.commit() #PostgreSQL은 sqlite랑 다르게 commit을 해야 GUI로 데이터베이스가 update된 것을 확인할 수 있음.
connection.close()