본문 바로가기
ML & DL

Python

by jun_code 2022. 5. 15.

함수

  • Mutable과 Immutable의 차이를 알아야 함
  • Mutable : 리스트, 딕셔너리, 집합
  • Immutable : 숫자형, 문자열, 튜플
    • 함수의 매개변수로 리스트나 집합, 딕셔너리를 조작하면 밖에서도 값이 변화함
def vector_sum(v, *vectors)됨
    res = [v[0],v[1]] # Mutable이기에 해주어야 되는 코드
    # res= v : 리스트(v)를 받아 변화하게 됨
    for vec in vectors:
        for i in range(len(vec)):
            res[i] += vec[i]
    return res
    
v1=[0, 1]
v2=[0.5, 0.5]
v3=[1, 0]
v4=[6, 4]
v5=[3.14, 2.72]

m1 = vector_sum(v1, v2, v3)
m2 = vector_sum(v1, v2, v3, v4)
m3 = vector_sum(v3, v5)
print(m1, m2, m3) # [1.5, 1.5] [7.5, 5.5] [4.140000000000001, 2.72]

 


 

 

 


 

 

파일

  • 파일을 사용하는 순서는 우리의 일상과 비슷하다
  • 파일을 열고 데이터를 읽거나 쓰고 파일을 닫아야 한다
  • 냉장고 문을 열고 음식을 꺼내고 문을 닫아야 하는 순서와 동일하게 이해하면 편할 것이다

파일 읽기

  •  읽는 방법 : readline(), readlines(), read(), for line in f
f = open('new.txt', 'r')

while True:
    line = f.readline()
    if line == "":
        break
    print(line, end='')
f.close()

f = open('new.txt', 'r')
lines = f.readlines()
print(lines)
f.close() # ['1 line \n', '2 line \n', '3 line \n', '4 line \n', '5 line \n']
f = open("new.txt", "r")
data = f.read()
print (data, end='\t')
f.close() 
'''
1 line 
2 line 
3 line 
4 line 
5 line '''
f = open("new.txt", "r")
for line in f:
    print (line, end='')
f.close()

 

파일 쓰기

f = open("new.txt", 'w') # new.txt가 없으면 새로 생성

for i in range(1, 6):
    data = "%d line \n" %
    f.write(data) # 파일에 data를 넣음

f.close()

 

파일 내용 추가하기

  • 파일의 마지막에 내용을 추가함
f = open('new.txt', 'a')

for i in range(6, 11):
    data = "%d line\n" %i
    f.write(data)
f.close()

'''
1 line 
2 line 
3 line 
4 line 
5 line 
6 line
7 line
8 line
9 line
10 line '''

 

파일을 열고 자동으로 닫기용 : with ~ as

  • with open()  as 사용
with open('new.txt', 'w') as f:
    f.write('Python is fun')

파일 존재 확인하기용 : import os 이용

  • os를 이용해 파일이 있는지 확인하기
import os
os.path.exists('new.txt') #True

외부에서 파일 불러오기

  • 터미널에서 값을 입력하고 출력하기

외부에서 파일 복사하기 : sys.argv 이용

# import sys

# f1 = open('new.txt', 'r')
# f2 = open('new1.txt', 'w')

# for line in f1:
#     f2.write(line)
    
# f2.close()
# f1.close()

#########################################
# 터미널 입력 : python sys1.py new.txt new2.txt
import sys

f1 = open(sys.argv[1], 'r')
f2 = open(sys.argv[2], 'w')

for line in f1:
    f2.write(line)
    
f2.close()
f1.close()

모듈 불러와서 실행하기

  • sys.argv : 리눅스 쉘에서 입력한 것
  • python ex1.py text1.txt ..
# 쉘 입력 : python ex1.py text1.txt text2.txt
import sys

f1 = open(sys.argv[1], 'r') # sys.argv[1] : text1.txt
f2 = open(sys.argv[2], 'w') # sys.argv[2] : text2.txt

for line in f1:
    f2.write(line)
    
f2.close()
f1.close()

 

객제 지향 프로그래밍 : Object-Oriented Programming

 

  • 객체 : 모종의 변수와 함수를 담는 추상적인 개념
  • 일상 생활의 문제를 사람의 시각에서 사물을 바라보는 관점을 데이터와 함수로  프로그램을 설계하는 것

 

클래스

  • 데이터와 함수를 묶어 객체로 만들어 주는 개념 => 객체의 틀을 정의
  • 변수와 메소드로 구성됨
  • 들여쓰기가 시작되는 것부터 Class가 정의되고 들여쓰기가 끝나면 정의가 종료
class Dog:
    name = 'Mon' # 데이터 어트리뷰트 : 변수
    
    def bark(self): # 메서드 어트리뷰트 : 함수
        return 'wal wal'
    
dog1 = Dog()
print(dog1.bark())
print(dog1.name) 

## 출력 ##
# wal wal
# Mon

특수 메서드 : Method Object

  • '__메서드이름__' 형태의 이름을 가짐
    • 내장 함수와 동일하게 미리 동작이 정의되어 있고 자동으로 작동함
  • __init__
    • 인스턴스 생성 시, 자동으로 호출되는 메서드
    • 인스턴스가 가질 여러 어트리뷰트를 초기화(지정)해주는 역할
class Building:
    def __init__ (self, name='공학1동', h=3, elev=True):
        self.name = name
        self.h = h
        self.elev = elev
    
    def get_info(self):
        print('건물 이름 :', self.name)
        print('건물 층 수 :', self.h)
        print('엘리베이터 유무 :', self.elev)

a = Building()
b = Building('공학2동', 10)

a.get_info()
print()
b.get_info()

## 출력 ##
# 건물 이름 : 공학1동
# 건물 층 수 : 3
# 엘리베이터 유무 : True

# 건물 이름 : 공학2동
# 건물 층 수 : 10
# 엘리베이터 유무 : True

메서드 객체 : Method Object

  • 클래스에 종속되어 있는 함수
    • 대상이 되는 객체가 있어야 사용 가능하며 모든 메소드는 반드시 인자가 존재해야 함
    • self : 객체를 가리키는 것(자기자신)
class person:
    def __init__(self, name='홍길동', age=24,height=182, weight=75):
        self.name = name
        self.age = age
        self.height = height
        self.weight = weight
        
    def add_age(self):
        self.age += 1
    
    def change_height(self, h):
        self.height = h
    
    def print_att(self):
        print(self.name, self.age, self.height, self.weight)

a = person('홍길동', 25, 150, 50)
a.print_att()

# 1년 후
a.add_age()
a.print_att()

## 출력 ##
# 홍길동 25 150 50
# 홍길동 26 150 50

클래스와 인스턴스 변수

  • 인스턴스 데이터 : 인스턴스가 가지는 데이터
  • 클래스 데이터 : 클래스의 모든 인스턴스가 공유하는 데이터(=메서드 어트리뷰트)
class Dog:
    kind = 'canine'
    
    def __init__(self, name):
        self.name = name
        
d = Dog('Fido')
e = Dog('Buddy')

print(d.kind, e.kind) # 클래스 데이터
print(d.name, e.name) # 인스턴스 데이터

## 출력 ##
# canine canine
# Fido Buddy
  • 클래스 변수 : Mutable vs Immutable
    • string 타입(Immutable)은 수정이 불가 => 새로운 변수를 생성하고 변수에 귀속하는 것
    • list(Mutable)는 수정이 가능 => 직접 수정 가능!!
# Immutable

class Dog:
    tricks = []
    
    def __init__(self, name):
        self.name = name
        
    def add_trick(self, trick):
        self.tricks.append(trick)
        
d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll')
e.add_trick('play dead')

print(d.tricks)

## 출력 ##
# ['roll', 'play dead']
# Mutable

class Dog:
    
    def __init__(self, name):
        self.name = name
        self.tricks = []
        
    def add_trick(self, trick):
        self.tricks.append(trick)
        
d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll')
e.add_trick('play dead')

print(d.tricks)

## 출력 ##
# ['roll']

 

상속

  • 기존 클래스의 속성을 물려 받아 새로운 클래스를 만드는 것
    • 새로운 클래스가 기존 클래스의 모든 변수와 메서드를 가짐
    • 다중 클래스도 상속이 가능함 => ','로 구분
class A:
    a = 1
    def print_a(self):
        print('A')
        
class C(A): # C는 A를 상속
    c=2
    def print_c(self):
        print('C')
        
c = C()
# Class.mro() : 상속을 여러개 받은 경우 앞에 있는 클래스가 우선시됨
print(C.mro()) # [<class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
print(A.mro()) # [<class '__main__.A'>, <class 'object'>]

메소드 오버라이딩

  • 기존 클래스의 메서드를 상속 클래스에서 재정의 하는 것
    • 재정의 하지 않은 것은 기존 클래스 그대로 사용
    • 오버라이딩을 한 경우, 기존 클래스의 메서드를 사용하자고자 하는 경우 super() 사용
class A:
    def __init__(self):
        print('This is [A], [__init__] function')
        self.var1 = 0
        self.var2 = 0
    
class B(A):
    def __init__(self):
    	# super().__init__()를 주석처리하면, A,B 한번씩 실행됨
        super().__init__() # 기존 클래스(A) 것 사용
        print('This is [B], [__init__] function')
        self.var3 = 0
        self.var4 = 0
        
a = A()
b = B()

## 출력 ##
# This is [A], [__init__] function
# This is [A], [__init__] function
# This is [B], [__init__] function
class BankAccount:
    def __init__(self, balance = 0, name='none'):
        self.name = name
        self.balance = balance
    
    def deposit(self, money):
        self.balance += money
        
    def withdraw(self, money):
        if self.balance < money:
            print('잔액 부족')
        else:
            self.balance -= money
        
    def get_info(self):
        print('이름 :', self.name)
        print('잔고 :', self.balance)

class MinimumBalanceAccount(BankAccount):
    def __init__(self, balance =0, name='none', min_bal=0):
        super().__init__(balance, name) # 그대로 상속받기
#         self.balance = balance
#         self.name = name
        self.min_bal = 0
    
#    def deposit() : 안 바꿔도 됨

    def withdraw(self, money):
        if self.balance - money < self.min_bal:
            print('최소 잔액을 유지해야 합니다')
        else:
            self.balance -= money
    
    def get_info(self):
        super().get_info()
        print('최소 잔액 :', self.min_bal)
        
a = MinimumBalanceAccount(1000, '이준영', 500)
a.deposit(1000)
print(a.balance)
a.withdraw(1900)
print(a.balance)
a.get_info()

## 출력 ##
# 2000
# 100
# 이름 : 이준영
# 잔고 : 100
# 최소 잔액 : 0

연산자 오버로딩

  • Python 연산자는 모두 내장된 특수 메소드를 호출함
  • 해당 메소드를 Override 하는 것으로 기능을 변경할 수 있음

class BankAccount:
    def __init__(self, balance = 0, name='none'):
        self.name = name
        self.balance = balance
    
    def deposit(self, money):
        self.balance += money
    
    def __add__(self, amount)행 # 연산자 오버라이딩
        self.deposit(amount)
    
    def withdraw(self, money):
        if self.balance < money:
            print('잔액 부족')
        else:
            self.balance -= money
        
    def get_info(self):
        print('이름 :', self.name)
        print('잔고 :', self.balance)
        
a = BankAccount(1000, 'A')
print(a.balance)
a + 1000 # 연산자 오버라이딩 수행
print(a.balance)

## 출력 ##
# 1000
# 2000

 

 

 

'ML & DL' 카테고리의 다른 글

이미지 분류  (0) 2022.05.12
keras에 사용되는 용어  (0) 2022.05.11