1. Class
● Class : 변수와 함수 묶어 코드 작성하는 방법
●객체지향 구현하는 문법
-객체지향 : 실제 세계를 모델링하여 프로그램을 개발하는 개발 방법론
(※가장 깔끔한 객체지향언어 JAVA)
협업 용이하게 하기 위함
#함수 사용법 :
▶ 함수선언(코드 작성) > 함수호출(코드실행)
#클래스 사용법 :
▶ 클래스선언(코드 작성) > 객체 생성(메모리 사용) > 메서드 실행(코드 실행)
여러 개의 메서드 선언 원하는 메서드만 실행
▶ 클래스선언(설계도 작성) > 객체 생성(자원 사용) > 메서드 실행(제품 생산 & 기능 사용)
#메서드 : 클래스 안에서 선언된 함수는 메서드라고함.
클래스 밖에서 선언된 함수는 함수.
메서드에서 변수는 재료, 함수는 기능
#식별자 컨벤션
▶ 변수, 함수 : snake_case
▶ 클래스 : PascalCase, UpperCamelCase
● 클래스 선언 예시_(계산기 설계 : Calulator) +dir( )함수
class Calculator :
number1, number2 = 1, 2 # 변수 2개
def plus(self): #함수 2개
return self.number1 + self.number2
def minus(self):
return self.number1 - self.number2
calc1 = Calculator()
calc2 = Calculator()
type(calc1)
--------------------
__main__.Calculator
※dir( ) : 객체에 들어있는 변수를 출력
[var for var in dir(calc1) if var[0] != '_']
calc1.number1, calc1.number2 #calc1이라는 객체안에 number1이라는 변수,
#calc1이라는 객체안에 number2라는 변수
-------------------------------------------------------------------
(1, 2)
calc1.plus(), calc1.minus()
---------------------------
(3, -1)
calc1.number1, calc1.number2, calc2.number1, calc2.number2
-----------------------------------------------------------
(1, 2, 1, 2)
calc1.number1 = 20
calc1.number1, calc1.number2, calc2.number1, calc2.number2
------------------------------------------------------------
(20, 2, 1, 2)
calc1.plus()
------------
22
●self : 객체 자신
거의 다 이해되긴 하는데 self 부분은 잘 이해가 안된다..나중에 다시 공부해 봐야겠다..
※ 하기 사이트 참고하기
※파이썬 코딩 도장: 34.2 속성 사용하기 (dojang.io)
Calculator.plus() : self.number1 + self.number2
calc1.plus() : self == calc1
- self.number1 +self.number2 > calc1.number1 + calc1.number2
● 클래스 선언 예시_ (은행 계좌 : Account)
class Account:
balance = 0
def insert(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
else:
print(f'잔액이 {amount - balance}원 부족합니다.')
account_1 = Account()
account_2 = Account()
account_1.balance, account_2.balance
-------------------------------------
(0, 0)
# 메서드실행 : 코드실행 : 기능 사용
account_1.insert(10000)
account_1.balance, account_2.balance
------------------------------------
(10000, 0)
●스페셜 메서드:
▶특별한 기능을 하는 메서드 : 앞뒤로 __를 붙임
●생성자 메서드: __init__()
▶ 객체를 생성할 때 실행되는 메서드
▶ 변수의 초기값을 설정할 때 주로 사용
▶ 불량 객체(메서드 사용 X)가 만들어질 확률을 줄여줌.
● 생성자 메서드 사용 예시:
class Account:
def __init__(self, balance = 20000):
self.balance = balance
def insert(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
else:
print(f'잔액이 {amount - self.balance}원 부족합니다.')
account = Account()
account.insert(3000)
account.balance
---------------
23000
클래스는 사용자정의 데이터 타입이다. |
※account의 데이터 타입
1) account의 데이터 타입 ▶ Account
2) account 객체가 만들어진 클래스 ▶ Account
3) 데이터 타입 == 클래스 ▶ 클래스 == 데이터타입
4) Account 클래스는 우리가 만듦 ▶ 사용자 정의
5) ▶클래스는 사용자정의 데이터 타입
# account = Account()
type(account)
---------------------
__main__.Account
※data의 데이터 타입
data = [1, 2, 3]
type(data)
-----------------
list
※account의 메서드
[var for var in dir(account) if var[0] != '_']
-----------------------------------------------
['balance', 'insert', 'withdraw']
※data의 메서드
print([var for var in dir(data) if var[0] != '_'])
--------------------------------------------------
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
※ 데이터 타입의 메서드를 암기할 필요 X
●객체의 데이터 타입에 따라서 사용할 수 있는 변수, 메서드가 다르다.
data1, data2 = 'python', [1, 2, 3]
print(type(data1), type(data2))
print([var for var in dir(data1) if var[0] != '_'])
print([var for var in dir(data2) if var[0] != '_'])
----------------------------------------------------
<class 'str'> <class 'list'>
['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
●클래스 == 데이터 타입 최종정리
# C언어로 만들어진 클래스는 앞이 소문자
# python으로 만들어진 클래스는 앞이 대문자
# ex
# import numpy as np
# arr = np.array([1, 2, 3])
# type(arr)
●추가적인 스페셜 메서드
__add__() : + 연산자 정의
__str__() : print() 함수 실행 정의
d1, d2, d3, d4 = 1, 2, '3', '4'
d1 + d2 , d3 + d4
-------------------------------
(3, '34')
d1 + d2 : d1.__add__(d2) : d1.__add__() : int 클래스의 __add__() 메서드
d3 + d4 : d3.__add__(d4) : d3.__add__() : str 클래스의 __add__() 메서드>
데이터 타입에 따라서 수행되는 __add__() 메서드가 다르다.
d5, d6 = [1,2], [3, 4]
d5 + d6
----------------------
[1, 2, 3, 4]
●덧셈연산 하지만 뺄셈이 수행되는 객체 생성 예제
class Number:
def __init__(self,data):
self.data =data
def __add__(self,obj):
return self.data - obj.data
def __str__(self):
return str(self.data)
def __repr__(self):
return str(self.data)
# obj.data는 메서드가 실행될때 받아온 파라미터의 obj 객체의 data 변수를 의미합니다.
# num1 + num2 를 하면 obj 에 num2 객체가 들어갑니다
number1 = Number(10)
number2 = Number(3)
number1.data, number2.data
---------------------------
(10, 3)
number1 + number2
------------------
7
2. 상속
●상속 : 다른 클래스의 변수(메서드)를 가져와서 사용하는 방법
#iPhone1 : call
#iPhone2 : call, send_msg
#iPhone3 : call, send_msg, internet
class iPhone1:
def call(self):
print('calling!')
class iPhone2:
def call(self):
print('calling!')
def send_msg(self):
print('send_msg!')
class iPhone3:
def call(self):
print('calling!')
def send_msg(self):
print('send_msg!')
def internet(self):
print('internet!')
# 상속 사용
class iPhone1:
def call(self):
print('calling!')
class iPhone2(iPhone1):
def send_msg(self):
print('send_msg!')
class iPhone3(iPhone2):
def internet(self):
print('internet!')
# 코드의 중복 방지
iphone1 = iPhone1()
iphone2 = iPhone2()
iphone3 = iPhone3()
def show_vars(obj):
return [var for var in dir(obj) if var[0] != '_']
show_vars(iphone1), show_vars(iphone2), show_vars(iphone3)
-----------------------------------------------------------
(['call'], ['call', 'send_msg'], ['call', 'internet', 'send_msg'])
# 오버 라이딩
# 상속 사용 ----- 나중에 내용 추가는 가능 ! 제외하고 상속은 X
class iPhone1:
def call(self):
print('calling!')
class iPhone2(iPhone1):
def send_msg(self):
print('send_msg!')
class iPhone3(iPhone2):
def call(self):
print('video calling!') # ---> 오버라이딩
def internet(self):
print('internet!')
오버라이딩 후
iphone3.call()
----------------
video calling!
●다중 상속
class Human:
def walk(self):
print('walking!')
class Korean:
def eat(self):
print('eat kimchi!')
class Indian:
def eat(self):
print('eat curry!')
class Jin(Korean, Human):
def skill(self):
print('coding')
jin = Jin()
show_vars(jin)
-------------------------------
['eat', 'skill', 'walk']
class Anchel(Indian, Human):
def skill(self):
print('speak english!')
anchel = Anchel()
show_vars(anchel)
---------------------------------
['eat', 'skill', 'walk']
jin.eat()
anchel.eat()
-------------
eat kimchi!
eat curry!
3. 데코레이터
● 데코레이터 : 함수에서 중복되는 코드를 빼서 데코레이터 함수로 만들어 코드를 작성하는 방법
● 원래 있던 함수에 새로운 기능을 추가한 함수로 변경할 때 주로 사용
def func1():
print('code1')
print('code2')
print('code3')
def func2():
print('code1')
print('code4')
print('code3')
def deco(func):
def wrapper(*args, **kwargs):
print('code1')
func() # == func1() : print('code2') == func2() : print('code4')
print('code3')
return wrapper
# deco 함수의 파라미터 func에 func1이 들어감
# func1 함수는 deco 함수의 return 함수인 wrapper 함수로 변경
# python에만 있는 문법 , 여러개의 데코함수 추가 가능
@deco
def func1():
print('code2')
@deco
def func2():
print('code4')
func1()
func2()
-----------------------------------------------------
code1
code2
code3
code1
code4
code3
'Python > ▶ Python' 카테고리의 다른 글
TIL ⑤일차 (0) | 2023.01.06 |
---|---|
TIL ③일차 (0) | 2023.01.04 |
②일차 Quiz - 윤년, Fizzbuzz, left-shift (0) | 2023.01.03 |
②일차 Quiz - 아이폰과 아이패드 (0) | 2023.01.03 |
TIL ②일차 (2) | 2023.01.03 |