190일차 백엔드 Flask - 정리 3

190일차 백엔드 Flask - 정리 3

//==========클래스==========

클래스도 변수/함수와 마찬가지로 유일한 이름을 지어줘야 함 class 에 attribute(속성=변수)/method(함수)를 아직 안넣은 상태이므로, 클래스에 내용이 없기에 임의로 pass 를 넣어 클래스 선언이 끝났음을 알려줌 클래스명은 PEP Coding Convention에 가이드된 대로 각 단어의 첫 문자를 대문자로 하는 CapWords 방식을 사용

만들어진 클래스는 객체 생성이 가능

객체도 변수/함수/클래스와 마찬가지로 유일한 이름을 지어줘야 함 함수와 마찬가지로 인수를 넣을 수 있음

attribute 넣어보기 (width, height, color)

class Quadrangle:

def init(self, width, height, color):

self.width = width

self.height = height

self.color = color

square1 = Quadrangle(12, 12, 'red')

square2 = Quadrangle(10, 10, 'blue')

객체의 attribute 접근하기

square1.color

print (square1.height, square2.height)

//==========Method(함수)==========

파이썬 method는 항상 첫 번째 파라미터로 self 사용 인자가 필요없을 때에도 self는 사용 클래스의 attribute는 내부에서 접근시, self.attribute명 으로 접근 //==========상속========== 추상화(abstraction): 여러 클래스에 중복되는 속성, 메서드를 하나의 기본 클래스로 작성하는 작업 상속(inheritance): 기본 클래스의 공통 기능을 물려받고, 다른 부분만 추가 또는 변경하는 것 이 때 기본 클래스는 부모 클래스(또는 상위 클래스), Parent, Super, Base class 라고 부름

기본 클래스 기능을 물려받는 클래스는 자식 클래스(또는 하위 클래스), Child, Sub, Derived class 라고 부름 코드 재사용이 가능, 공통 기능의 경우 기본 클래스 코드만 수정하면 된다는 장점 부모 클래스가 둘 이상인 경우는 다중 상속 이라고 부름

super()

자식 클래스에서 부모 클래스의 method를 호출할 때 사용 super().부모 클래스의 method명

self

self는 현재의 객체를 나타냄 self.method명 또는 attribute명 으로 호출함 C++/C#, Java언어에서는 this 라는 키워드를 사용함 //==========클래스 변수와 인스턴스 변수========== 클래스 변수: 클래스 정의에서 메서드 밖에 존재하는 변수 해당 클래스를 사용하는 모두에게 공용으로 사용되는 변수

클래스 변수는 클래스 내외부에서 "클래스명.변수명" 으로 엑세스 가능 인스턴스 변수: 클래스 정의에서 메서드 안에서 사용되면서 "self.변수명"처럼 사용되는 변수 각 객체별로 서로 다른 값을 가짐

클래스 내부에서는 self.인스턴스변수명 을 사용하여 엑세스, 클래스 밖에서는 객체명.인스턴스변수명 으로 엑세스

class Figure:

count = 0 # 클래스 변수

def __init__(self, width, height): # width, height 주 생성자(initializer) # self.* : 인스턴스변수 self.width = width self.height = height //==========Method(인스턴스, 스태틱, 클래스)==========

instance method : 해당 객체 안에서 호출 (지금까지 다룬 self.메서드명을 의미함) 해당 메서드를 호출한 객체에만 영향을 미침

객체 속성에 접근 가능 static method: 객체와 독립적이지만, 로직상 클래스내에 포함되는 메서드 self 파라미터를 갖고 있지 않음

객체 속성에 접근 불가

정적 메서드는 메서드 앞에 @staticmethod 라는 Decorator를 넣어야 함

클래스명.정적메서드명 또는 객체명.정적메서드명 둘 다 호출 가능 class method : 해당 class 안에서 호출 (해당 클래스로 만들어진 객체에서 호출되지 않고, 직접 클래스 자체에서 호출) self 파라미터 대신, cls 파라미터를 가짐

클래스 변수 접근 가능하며 cls.클래스변수명 으로 엑세스 가능 단, 객체 속성/메서드는 접근 불가

클래스 메서드는 메서드 앞에 @classmethod 라는 Decorator를 넣어야 함

클래스명.클래스메서드명 또는 객체명.클래스메서드명 둘 다 호출 가능 //==========범위==========

instatnce method : 객체 안에서만 동작

class method : 해당 클래스만을 범위로 가진다.

static method : class와 instatnce의 범위를 넘어선다.

예시)

SuperClass # 부모

SubClass # 자식

각각의 Class 메소드는, 각각의 부모 클래스, 자식 클래스에 국한된다.

static 메소드는, 부모 클래스, 자식클래스 상관없이 전체를 범위를 가진다.

//==========static, class method의 차이==========

범위의 차이 예시1) class Figure: @classmethod def set_name(cls, name): cls.name = name

class Circle(Figure):

pass

Figure.set_name("figure")

print (Figure.name, Circle.name) # output : figure figure

Circle.set_name("circle")

print (Figure.name, Circle.name) # output : figure circle

예시2)

class Figure:

@staticmethod

def set_name(name):

Figure.name = name

class Circle(Figure):

pass

Figure.set_name("figure")

print (Figure.name, Circle.name) # output : figure figure

Circle.set_name("circle")

print (Figure.name, Circle.name) # output : circle circle

//==========블로그 구현을 위한 클래스==========

MVC 패턴중 Control 기능 구현을 위해 클래스를 사용

클래스명.함수 형태로 코드 작성이 가능하여, 코드만 보더라도 어떤 코드인지 알 수 있고, 함수별 구분이 가능함 클래스내에 유사한 기능을 넣어서 기능별로 구현 및 유지보수가 유리함 //==========사용자(email) 클래스========== mysql schema

CREATE TABLE user_info (

USER_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,

USER_EMAIL VARCHAR(100) NOT NULL,

BLOG_ID CHAR(4),

PRIMARY KEY(USER_ID)

); User class

class User(UserMixin): def init(self, user_id, user_email, blog_id): self.id = user_id self.user_email = user_email self.blog_id = blog_id def get_id(self): return str(self.id) @staticmethod

def get(user_id): mysql_db = conn_mysqldb() db_cursor = mysql_db.cursor() sql = "SELECT * FROM user_info WHERE USER_ID = '" + \ str(user_id) + "'" db_cursor.execute(sql) user = db_cursor.fetchone() if not user: db_cursor.close() return None print(user) user = User(user_id=user[0], user_email=user[1], blog_id=user[2]) db_cursor.close() return user @staticmethod

def find(user_email): mysql_db = conn_mysqldb() db_cursor = mysql_db.cursor() sql = "SELECT * FROM user_info WHERE USER_EMAIL = '" + \ str(user_email) + "'" db_cursor.execute(sql) user = db_cursor.fetchone() if not user: db_cursor.close() return None print(user) user = User(user_id=user[0], user_email=user[1], blog_id=user[2]) db_cursor.close() return user @staticmethod

def create(user_email, blog_id): user = User.find(user_email) if user == None: mysql_db = conn_mysqldb() db_cursor = mysql_db.cursor() sql = "INSERT INTO user_info (USER_EMAIL, BLOG_ID) VALUES ('%s', '%s')" % ( str(user_email), str(blog_id)) db_cursor.execute(sql) mysql_db.commit() return User.find(user_email) else: return user blog 세션 관리 클래스

class BlogSession():

blog_page = {'A': 'blog_A.html', 'B': 'blog_B.html'}

session_count = 0 @staticmethod

def save_session_info(session_ip, user_email, webpage_name): now = datetime.now() now_time = now.strftime("%d/%m/%Y %H:%M:%S") mongo_db = conn_mongodb() mongo_db.insert_one({'session_ip': session_ip, 'user_email': user_email, 'page': webpage_name, 'access_time': now_time}) @staticmethod

def get_blog_page(force=None): print(force) if force == None: if BlogSession.session_count == 0: BlogSession.session_count = 1 return 'blog_A.html' else: BlogSession.session_count = 0 return 'blog_B.html' else: return BlogSession.blog_page[force]

from http://kwonputer.tistory.com/213 by ccl(A) rewrite - 2021-03-22 21:26:18