# 1. 싱글톤 클래스 만들기
class Singleton(type): # Type을 상속받음
__instances = {} # 클래스의 인스턴스를 저장할 속성
def __call__(cls, *args, **kwargs): # 클래스로 인스턴스를 만들 때 호출되는 메서드
if cls not in cls.__instances: # 클래스로 인스턴스를 생성하지 않았는지 확인
cls.__instances[cls] = super().__call__(*args, **kwargs) # 생성하지 않았으면 인스턴스를 생성하여 해당 클래스 사전에 저장
return cls.__instances[cls] # 클래스로 인스턴스를 생성했으면 인스턴스 반환
# 2. 싱글톤 클래스 만들기
class PrintObject(metaclass=Singleton): # 메타클래스로 Singleton을 지정
def __init__(self):
print("This is called by super().__call__")
# 3. 싱글톤 객체 만들기 (object1, object2 모두 동일)
object1 = PrintObject()
object2 = PrintObject()
print(object1)
print(object2)
class Observer:
def __init__(self):
self.observers = list()
self.msg = str()
def notify(self, event_data):
for observer in self.observers:
observer.notify(event_data)
def register(self, observer):
self.observers.append(observer)
def unregister(self, observer):
self.observers.remove(observer)
class SMSNotifier:
def notify(self, event_data):
print(event_data, 'received..')
print('send sms')
class EmailNotifier:
def notify(self, event_data):
print(event_data, 'received..')
print('send email')
class PushNotifier:
def notify(self, event_data):
print(event_data, 'received..')
print('send push notification')
notifier = Observer()
sms_notifier = SMSNotifier()
email_notifier = EmailNotifier()
push_notifier = PushNotifier()
notifier.register(sms_notifier)
notifier.register(email_notifier)
notifier.register(push_notifier)
notifier.notify('user activation event')
class Student(object):
def __init__(self, name, age=20, height=180, weight=60, major='cs'):
self.name = name
self.age = age
self.height = height
self.weight = weight
self.major = major
student1 = Student('Dave')
print(student1.name)
print(student1.age)
print(student1.height)
print(student1.weight)
print(student1.major)
student1 = Student(major='ds', name='David')
print(student1.name)
print(student1.age)
print(student1.height)
print(student1.weight)
print(student1.major)
# 상세 클래스 만들기
class AndroidSmartphone:
def send(self, message):
print ("send a message via Android platform")
class WindowsSmartphone:
def send(self, message):
print ("send a message via Window Mobile platform")
class iOSSmartphone:
def send(self, message):
print ("send a message via iOS platform")
# 팩토리 클래스 만들기
class SmartphoneFactory(object):
def __init__(self):
pass
def create_smartphone(self, devicetype):
if devicetype == 'android':
smartphone = AndroidSmartphone() # <-- 실제 객체를 팩토리 클래스 안에서 만든다.
elif devicetype == 'window':
smartphone = WindowsSmartphone() # <-- 실제 객체를 팩토리 클래스 안에서 만든다.
elif devicetype == 'ios':
smartphone = iOSSmartphone() # <-- 실제 객체를 팩토리 클래스 안에서 만든다.
return smartphone
# 팩토리 클래스로 실제 상세 객체 만들기
smartphone_factory = SmartphoneFactory()
message_sender1 = smartphone_factory.create_smartphone('android')
message_sender1.send('hi')
message_sender2 = smartphone_factory.create_smartphone('window')
message_sender2.send('hello')
message_sender3 = smartphone_factory.create_smartphone('ios')
message_sender3.send('are you there?')
Figure - 클래스 이름 (별도 인자는 받지 않음) draw_shape(shape, color, x, y) shape 파라미터 - 도형 모양 의미 (string) 삼각형 그리기 - "triangle" 사각형 그리기 - "quadrangle" 오각형 그리기 - "pentagon" 육각형 그리기 - "hexagon" 원 그리기 - "circle" Color 파라미터 - 도형 색상 의미 (string) 빨강 - "red" 파랑 - "blue" 검정 - "black" x, y 파라미터 - 좌표를 의미 (숫자) clear_shape() 도형 삭제 (Turtle 라이브러리의 reset() 메서드 활용) move_shape() 기존 도형을 삭제된 듯 보이게하고, 새로운 위치에 동일한 도형을 그려주면 됨* 생각할 점: shape 파라미터 인자를 삼각형은 1, 사각형은 2 와 같이 인자값을 주면 동일하게 구동되도록 바꿔보세요
import requests
from bs4 import BeautifulSoup
res = requests.get('https://www.naver.com/')
soup = BeautifulSoup(res.content, 'html.parser')
# a 태그이면서 href 속성 값이 특정한 값을 갖는 경우 탐색
link_title = soup.select("#PM_ID_ct > div.header > div.section_navbar > div.area_hotkeyword.PM_CL_realtimeKeyword_base > div.ah_roll.PM_CL_realtimeKeyword_rolling_base > div > ul > li")
for num in range(len(link_title)):
# link_title 은 리스트 타입으로 개별 태그셋을 저장합니다.
# print(type(link_title))
# 각 태그셋은 string이 아니라 BeautifulSoup의 element.Tag 라는 객체입니다.
# print(type(link_title[0]))
# 그래서 각 태그셋에 다시 find(), find_all() 과 같은 BeautifulSoup 메서드를 사용할 수 있음을 확인할 수 있습니다.
link_title_each = link_title[num].find_all('span')
print(link_title_each[1].get_text())
import xlsxwriter
workbook = xlsxwriter.Workbook('TEST.xlsx')
worksheet = workbook.add_worksheet()
worksheet.set_column(0, 0, 80)
worksheet.write(1, 1, '타이틀')
for num in range(len(title_list)):
worksheet.write(num + 2, 1, title_list[num])
workbook.close()