파이썬 객체지향 프로그래밍(Object-Oriented Programming, OOP)은 프로그램을 개발할 때 데이터와 해당 데이터를 처리하는 메서드(함수)를 함께 묶어서 객체(Object)로 표현하는 프로그래밍 방법론 이러한 객체는 클래스(Class)에 의해 정의되며, 클래스는 객체를 만들기 위한 설계 도면이라고 생각
class Animal: #클래스
def __init__(self, name, sound):
self.name = name
self.sound = sound
def make_sound(self): #메서드
print(f"{self.name} makes a sound: {self.sound}")
# Animal 클래스를 상속받아 새로운 클래스를 만듭니다.
class Dog(Animal):
def wag_tail(self):
print(f"{self.name} wags its tail")
class Cat(Animal):
def purr(self):
print(f"{self.name} purrs")
# Animal 클래스의 객체 생성
generic_animal = Animal("Generic Animal", "Some Sound")
generic_animal.make_sound()
#
# Dog 클래스의 객체 생성
my_dog = Dog("Buddy", "Woof")
my_dog.make_sound()
my_dog.wag_tail()
# 괄호가 없는 튜플
tuple_test = 10,20,30,40
print(tuple_test)
print(type(tuple_test))
# 괄호가 없는 튜플 활용
a,b = 10,20
print(a,b)
a,b = b,a
print(a,b)
def test():
print("A통과")
yield 1
print("B통과")
yield 2
print("C통과")
yield 3
print("sss")
yield 4
print("a")
yield "abc"
output = test()
print("D통과")
a = next(output)
print(a)
b = next(output)
print(b)
c = next(output)
print(c)
d = next(output)
print(d)
next(output)
#결과
D통과
A통과
1
B통과
2
C통과
3
sss
4
a
'abc'
#람다
power = lambda x: x * x
under_3 = lambda x: x<3
list_input_a = [1,2,3,4,5]
output_a = map(power, list_input_a)
print(output_a)
print(list(output_a))
output_b = filter(under_3, list_input_a)
print(output_b)
print(list(output_b))
##인라인 람다
output_aa = map(lambda x : x * x, list_input_a)
print(output_aa)
print(list(output_aa))
output_bb = filter(lambda x: x <3 , list_input_a)
print(output_bb)
print(list(output_bb))
## 매개변수가 여러개인 람다
list_edu1 = [1,2,3]
list_edu2 = [4,5,6]
output_c = map(lambda x, y : x+y, list_edu1,list_edu2)
print(list(output_c))
#<결과값>
<map object at 0x10a7b4b80>
[1, 4, 9, 16, 25]
<filter object at 0x10a7b59c0>
[1, 2]
<map object at 0x10a78a920>
[1, 4, 9, 16, 25]
<filter object at 0x10a7b6920>
[1, 2]
[5, 7, 9]
num = list(range(1,10+1))
print("홀수만 추출",list(filter(lambda x : x%2==1, num)))
print("3이상 7 이하만 추출", list(filter(lambda x: 3<=x<=7, num)))
print("제곱해서 50미만 추출", list(filter(lambda x: x*x< 50, num )))
from flask import Flask
from urllib import request
from bs4 import BeautifulSoup
app = Flask(__name__)
@app.route("/")
def hello():
target = request.urlopen("https://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp?stnID=108")
soup = BeautifulSoup(target, "html.parser")
output = ""
for location in soup.select("location"):
output += "<h3>{}<h3>".format(location.select_one("city").string)
output += "날씨: {}<br/>".format(location.select_one("wf").string)
output += "날짜: {}<br/>".format(location.select_one("tmEf").text)
output += "최저/최고 기온 : {}/{}"\
.format(\
location.select_one("tmn").string,\
location.select_one("tmx").string\
)
output += "<hr/>"
return output
함수에 사용되는 데코레이터
함수나 메서드 위에 직접 적용해야함.
함수 데코레이터
def test(function):
def wrapper():
print("인사가 시작되었습니다.")
function()
print("인사가 종료되었습니다.")
return wrapper
@test
def hello():
print("hello")
hello()
import time
def measure_time(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Execution time of {func.__name__}: {end_time - start_time} seconds")
return result
return wrapper
@measure_time
def add_numbers(a, b):
time.sleep(1)
return a + b
result = add_numbers(3, 5)
print("Result:", result)
클래스 데코레이터
파이썬에서 사용되는 특별한 변수
현재 모듈 혹은 스크립트의 이름을 나타낼 때(즉 모듈인지, 엔트리포인트인지 구분)
다른 모듈에서 import될 때는 해당 모듈의 이름이 부여됨
모듈이 스크립트로 직접 실행되는지, 다른 모듈에 의해 임포트되어 있는지 구분하여 코드를 실행하거나 테스트 할 수 있음