코딩하는 타코야끼

[스터디 노트] Week2_2일차[unit20 ~ 39] 본문

zero-base 데이터 취업 스쿨/스터디 노트

[스터디 노트] Week2_2일차[unit20 ~ 39]

가스오부시 2023. 7. 14. 23:19
728x90
반응형

1. 중급_5~6 [unit 20 ~ 28]


📍 객체와 메모리

  • 변수는 객체의 메모리 주소를 저장하고 이를 이용해서 객체를 참조한다.

📍얕은 복사 와 깊은 복사

  • 얕은 복사란, 객체 주소를 복사하는 것으로 객체 자체가 복사되지 않는다.
  • 깊은 복사란, 객체 자체를 복사하는 것으로 또 하나의 객체가 만들어진다.
# 선수의 원본 점수를 이용해서 평균을 출력하고
# 최고값과 최저값을 제외한 평균을 출력하는 프로그램을 만들어보자.
l = [7.9, 8.3, 8.7, 8.8, 8.9, 9.0, 9.1, 9.5]
copy_l = l.copy()

copy_l.sort()
copy_l.pop(0)
copy_l.pop()

o_total = round(sum(l), 2)
o_avg = round(o_total / len(l), 2)
print(f"original total: {o_total}")
print(f"original average: {o_avg}")

c_total = round(sum(copy_l), 2)
c_avg = round(c_total / len(copy_l), 2)
print(f"copy total: {c_total}")
print(f"copy avg: {c_avg}")

print(f"ori_avg - copy_avg: {o_avg - c_avg}")
>>>
original total: 70.2
original average: 8.78
copy total: 52.8
copy avg: 8.8
ori_avg - copy_avg: -0.02000000000000135

📍상속 이란

  • 클래스는 또 다른 클래스를 상속해서 내 것처럼 사용할 수 있다.
# 덧셈, 뺄셈 기능이 있는 클래스를 만들고
# 이를 상속하는 클래스를 만들어서 곱셈과 나눔셈 기능을 추가해 보자.

class Calculator_parent:
    
    def add(self, n1, n2):
        return n1 + n2
    
    def sub(self, n1, n2):
        return n1 - n2

# child 클래스는 parent 클래스를 상속한다.
class Calculator_child(Calculator_parent):
    
    def mul(self, n1, n2):
        return n1 * n2
    
    def div(self, n1, n2):
        return n1 / n2

cal = Calculator_child()

print(f"cal add: {cal.add(4, 6)}")
print(f"cal sub: {cal.sub(4, 6)}")
print(f"cal mul: {cal.mul(4, 6)}")
print(f"cal div: {cal.div(4, 6)}")
>>>
cal add: 10
cal sub: -2
cal mul: 24
cal div: 0.6666666666666666

📍 생성자

  • 객체가 생성될 때 생성자를 호출하면  __init( )__ 가 자동 호출된다.
class Print_info:
    
    def __init__(self):
        print("print info 예시")

example = Print_info()
>>>
print info 예시

📍 __init__( )

  • init( )가 속성을 초기화 한다.
class Print_info:
    
    def __init__(self):
        print("print info 예시")

example = Print_info()
>>>
print info 예시

📍 super( )

  • 상위 클래스의 속성을 초기화하기 위해서 super( )를 이용한다.
class Child:
    
    def __init__(self, cn1, cn2):
        print("print child numbers")
        self.cn1 = cn1
        self.cn2 = cn2

ch = Child(40, 50)
print(f"ch.cn1 : {ch.cn1}")
print(f"ch.cn2 : {ch.cn2}")
>>>
print child numbers
ch.cn1 : 40
ch.cn2 : 50

📍 다중 상속

  • 2개 이상의 클래스를 상속한다.

📍오버라이딩

  • 하위 클래스에서 상위 클래스의 메서드를 재정의(override)한다.

[출처: zero-base]


📍 추상클래스

  • 상위 클래스에서 하위 클래스에 메서드 구현을 강요한다.
  • 정의되어 있지 않은 class를 추상 클래스라 한다.
  • 어떠한 공통적인 기능을 사용하지만 각자 입맛에 맞게 써야 될 때 추상 클래스를 사용한다.

⚡️ 중요 메모

📎  클래스 상속

  • 클래스를 상속받을 경우 상속관계 꼭 정의하기

  • 클래스를 상속 받고 정의할 경우, super( )로 오버라이딩 하기

  • 다중 상속일 경우, 상속관계 및 오버라이딩 하기 예시


2. 중급_7 [unit 29 ~ 32]


📍 예외란

  • 예외란, 문법적인 문제는 없으나 실행 중 발생하는 예상하지 못한 문제이다.
  • 예외 관련 클래스는 Exception 클래스를 상속한다.

📍 예외처리

  • 예상하지 못한 예외가 프로그램 전체에 영향이 없도록 처리함.

📍 try ~ except

  • 예외 발생 예상 구문을 try ~ except로 감싼다.
nums = []
n = 1

while n < 6:
    try:
        user_n = int(input("input number: "))
    except:
        print("예외발생")
        continue
    nums.append(user_n)
    n += 1
print(f"nums: {nums}")
>>>
input number: 1
input number: a
예외발생
input number: 2
input number: 3
input number: jk
예외발생
input number: hn
예외발생
input number: 4
input number: 5
nums: [1, 2, 3, 4, 5]

📍 ~ else

  • 예외가 발생하지 않은 경우 실행하는 구문이다.

📍 finally

  • 예외 발생과 상관없이 항상 실행한다.
try:

except:

finally:
	print( ~ )

📍 Exception

  • 예외 담당 클래스 Exception

📍 raise

  • raise 키워드를 이용하면 예외를 발생시킬 수 있다.

📍 Exception 클래스

  • Exception 클래스를 상속해서 사용자 예외 클래스를 만들 수 있다.

[출처: zero-base]


3. 중급_8~9 [unit 33 ~ 39]


📍 기본함수

  • open( )
  • read( )
  • write( )
  • close( )

📍 파일 쓰기

  • write( ) 함수를 이용한 파일에 문자열 쓰기
file = open('/Users/Desktop/mose/zero-base/스터디노트/2주차/test.txt', "w")

str_cnt = file.write("Hello world~")
print(f"str_cnt: {str_cnt}")

file.close()
>>>
str_cnt: 12

📍 파일 읽기

  • read( ) 함수를 이용한 파일 문자열 읽기
file = open('/Users/Desktop/mose/zero-base/스터디노트/2주차/test.txt', "r")
str = file.read()
print(f"str: {str}")
>>>
str: Hello world~

📍 파일 모드

  • 파일 모드는 파일을 어떤 목적으로 open 할지 정한다.

📍 with ~ as문

  • with ~ as문을 이용하면 파일 닫기(close)를 생략할 수 있다.
with open(uri + "test.txt", 'r') as f:
    print(f.read())
>>>
안녕하세요.

📍 writelines( )

  • writelines( )는 리스트(List) 또는 튜플 데이터를 파일에 쓰기 위한 함수이다.
languages = ["java\\n", "c#\\n", "python\\n", "javascript\\n"]

with open(uri + "language.txt", "w") as f:
    f.writelines(languages)

with open(uri + "language.txt", "r") as f:
    print(f.read())
>>>
java
c#
python
javascript

📍 readlines( )

  • 파일의 모든 데이터를 읽어서 리스트 형태로 반환한다.
with open(uri + "language.txt", "r") as f:
    data = f.readlines()
    print(data)
>>>
['java\\n', 'c#\\n', 'python\\n', 'javascript\\n']

📍 readline( )

  • 한 행을 읽어서 문자열로 반환 한다.
with open(uri + "language.txt", "r") as f:
    line = f.readline()
    
    while line != "":
        print(f"line: {line}", end="")
        line = f.readline()
>>>
line: java
line: c#
line: python
line: javascript

⚡️실습 코드 파일⚡️

w2_2일차 스터디 노트[unit_20 ~ 39].ipynb
0.84MB

반응형