회고

- 코드를 짜면서 클래스를 나누는 것에 대한 의문이 생겼다. 객체지향적인 클래스는 무엇일까.. 나름대로 기준을 세우는데 코드를 짜다 보면 클래스가 잘못 구분되었다는 생각이 든다.
객체지향의 본질은 "현실에서 구분되는 개념"이라 한다. 너무 복잡하게 생각하지말고 하나하나 구분해보는 능력을 키워야겠다.
필기
스태틱메서드
- staticmethod는 객체와 아무런 관계가 없으며, self도 매개변수로 갖지 못한다.
- 객체를 안만들고 메서드를 사용하기 위해 사용
class Test:
def __init__(self, number):
self.number = number
def output(self):
print(self.number)
class Calculator:
def __init__(self, x, y):
self.x = x
self.y = y
def add(self):
return self.x + self.y
def sub(self):
return self.x - self.y
c1 = Calculator(4,5)
print(c1.add())
print(c1.sub())
class Calculator2:
def add(self, x, y):
return x + y
def sub(self, x, y):
return x - y
c2 = Calculator2()
print(c2.add(4,5))
print(c2.sub(4,5))
class Calculator3:
@staticmethod
def add(x,y):
return x + y
@staticmethod
def sub(x,y):
return x - y
@staticmethod
def mul(x,y):
return x * y
print(Calculator3.add(4,5))
print(Calculator3.sub(4,5))
print(Calculator3.mul(4,5))
클래스메서드
- 객체의 개수를 카운트하거나 제한하는 클래스를 만들고자 할 때 사용
class MyClass:
count = 0
@staticmethod
def addCount():
count += 1
@classmethod
def increase(cls):
cls.count += 1
MyClass.increase()
print(MyClass.count)
class SelfCount:
__count = 0
def __init__(self):
SelfCount.__count+=1
print(SelfCount.__count)
@classmethod
def count_output(cls):
print(cls.__count)
s1 = SelfCount()
SelfCount.count_output()
s1 = SelfCount()
SelfCount.count_output()
s1 = SelfCount()
SelfCount.count_output()
s1 = SelfCount()
SelfCount.count_output()
싱글톤
class Singleton:
__instance = None
@classmethod
@classmethod
def getInstance(cls):
if cls.__instance==None:
cls.__instance= cls.__new__(cls)
return cls.__instance
def display(self):
print("*************")
def __init__(self):
if Singleton.__instance is not None:
raise Exception("이 클래스는 반드시 getInstance로만 객체 생성이 가능합니다.")
s1 = Singleton.getInstance()
s1.display()
s2 = Singleton()
s2.display()
데코레이터
def decorator1(func):
def wrapper():
print("함수호출 전")
func()
print("함수호출 후")
return wrapper
@decorator1
def hello():
print("Hello")
hello()
import time
def time_decorator(callback):
def innerfunction():
callback()
start = time.time()
callback()
end = time.time()
print(f"{callback.__name__} 실행시간 : {end-start}초")
return innerfunction
def mydecorator(callback):
def wrapper(*args, **kwargs):
result = callback(*args, **kwargs)
return result
return wrapper
@mydecorator
def add(x, y):
return x + y
print(add(5,7))
"""
[Log] 함수이름 : sigma2
[Log] 입력값 : args = (10), kwargs = {}
[Log] 반환값 : 55
"""
def mylog(callback):
def wrapper(*args, **kwargs):
result = callback(*args, **kwargs)
print(f"[LOG] 함수이름 : {callback.__name__}")
print(f"[LOG] 입력값 : args {args} kwargs{kwargs}")
print(f"[LOG] 반환값 : {result}")
return result
return wrapper
@mylog
def sigma2(limit=10):
s = 0
for i in range(1, limit+1):
s += i
return s
print(sigma2(100) )
print(sigma2(10))
@mylog
def sub(a, b):
return a - b
print(sub(3,4))
과제
홈페이지_클래스
import random
import datetime
class Homepage:
def __init__(self):
self.membershipList = []
self.writingList = []
def printWriteInfo(self):
print("회원번호 : ")
print("제목 : ")
print("내용 : ")
print("작성일 : ")
print("조회수 : ")
def main(self):
print("============")
print("0. 창닫기")
print("1. 회원가입")
print("2. 로그인")
print("3. 관리자")
print("============")
sel = input("번호를 선택 : ")
while True:
if sel == "1":
print("회원가입 하실 정보를 입력해주세요.")
elif sel == "2":
print("id와 pw를 입력해주세요.")
elif sel == "3":
print("관리자모드로 접속합니다.")
elif sel > "3":
print("다시 입력하세요.")
return
elif sel == "0":
print("프로그램 종료")
break
class User:
def __init__(self, number, id, pw, name, phone, mail):
self.number = number
self.id = id
self.pw = pw
self.name = name
self.phone = phone
self.mail = mail
def printInfo(self):
print(f"회원번호 : {self.number}", end = "\t")
print(f"id : {self.id}", end = "\t")
print(f"pw : {self.pw}", end = "\t")
print(f"이름 : {self.name}", end = "\t")
print(f"전화번호 : {self.phone}", end = "\t")
print(f"메일 : {self.mail}")
class Post:
def __init__(self, number, title, content):
self.number = number
self.title = title
self.content = content
self.datetime = datetime.date.today()
self.count = 0
def printPost(self):
print(f"회원번호 : {self.number}", end = "\t")
print(f"제목 : {self.title}", end = "\t")
print(f"내용 : {self.content}", end = "\t")
print(f"게시일 : {self.datetime}", end = "\t")
print(f"조회수 : {self.count}")
class BoardSystem:
def __init__(self):
self.membershipList = []
self.postList = []
def signIn(self):
number = random.randint(1,1000)
id = input("id : ")
pw = input("pw : ")
name = input("이름 : ")
phone = input("전화번호 : ")
mail = input("이메일 : ")
user = User(number, id, pw, name, phone, mail)
self.membershipList.append(user)
def login(self):
id = input("id : ")
resultId = list(filter(lambda x : id in x.id, self.membershipList))
for id in enumerate(resultId):
pw = input("pw : ")
break
resultPw = list(filter(lambda x : pw in x.pw, self.membershipList))
for pw in enumerate(resultPw):
print(("===로그인 성공==="))
break
def writePost(self):
title = input("제목 : ")
content = input("내용 : ")
post = Post(title, content)
self.postList.append(post)
def viewPost(self):
if len(self.postList) == 0:
print("등록된 글이 없습니다.")
else:
for post in self.postList:
post.printPost()
def main(self):
while True:
print("1. 회원가입 2. 로그인 3. 글쓰기 4. 글목록보기 0. 종료")
sel = input("선택: ")
if sel == "1":
self.signIn()
elif sel == "2":
self.login()
elif sel == "3":
self.writePost()
elif sel == "4":
self.viewPost()
elif sel == "0":
print("프로그램 종료")
break
else:
print("잘못된 입력")
if __name__ == "__main__":
hpg = BoardSystem()
hpg.main()