python_basic_Exeption

python

Exception

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# /c/Users/brill/Desktop/PyThon_Function/venv/Scripts/python
# -*- coding : UTF-8

def error01():
a=10
a/0
#ZeroDivisionError: division by zero

def error02():
a= [1, 2, 3, 4, 5]
a[10]
#IndexError: list index out of range

def error03():
a = 1000
a + "Hello"
#TypeError: unsupported operand type(s) for +: 'int' and 'str'

def error04():
a=10
a+b
#NameError: name 'b' is not defined

if __name__ == "__main__":
error01()
error02()
error03()
error04()
print("program is done")

Exeption의 종류

java 의 try catch 구문과 같음

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# /c/Users/brill/Desktop/PyThon_Function/venv/Scripts/python
# -*- coding : UTF-8

def try_func(x, idx):
try:
return 100/x[idx]
except ZeroDivisionError:
print("did't divide zero")
except IndexError:
print("not in range of Index")
except TypeError:
print("there is type Error")
except NameError:
print("it is not definated parameter")
finally:
print("무조건 실행됨")


def main():
a = [50, 60, 0, 70]
print(try_func(a,1))

# Zero Division Error
print(try_func(a,0))

# Index Error
print(try_func(a,5))

# type Error
print(try_func(a, "hi"))


if __name__ == "__main__":
main()

어떻게던 프로그램이 돌아 갈 수 있도록
만들어 주는 것이 중요하다.




  • class 정리
  1. __init__ : set_name, set_id 해 주지 않고, 통합시켜주는 역할
  2. __eq__, __ne__ : 부등호 연산자
  3. 상속, 다형성(서로다른 클래스에서 공통으로 쓰는 함수)
  4. Exception
  5. class attribute / instance attribute / instance method 차이
  6. 추상 class (안배웠음)
  7. data incapsulation



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# /c/Users/brill/Desktop/PyThon_Function/venv/Scripts/python
# -*- coding : UTF-8

class SalaryExcept(ValueError): pass # 상속
class TipExept(SalaryExcept): pass # 상속

class Employee:

MIN_SALARY = 30000
MAX_Bonus = 20000

def __init__(self, name, salary = 30000):
self.name = name
if salary< Employee.MIN_SALARY:
raise SalaryExcept("급여가 너무 낮아요!")
self.salary = salary

def give_bonus(self, amount):
if amount > Employee.MAX_Bonus:
print("보너스가 너무 많아 ")
elif self.salary + amount < Employee.MIN_SALARY :
print("보너스 지급 후의 급여도 매우 낮다. ")
else:
self.salary += amount

if __name__ == "__main__":
emp = Employee("YH", salary= 10000)

try:
emp.give_bonus(70000)
except SalaryExcept:
print("Error Salary")

try:
emp.give_bonus(-10000)
except tipExcept:
print("Error Tip")

여전히 Error가 나는 코드
나는 Exception 안됨

python_basic_Bank

python

Bank _ 계좌 만들기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# /c/Users/brill/Desktop/PyThon_Function/venv/Scripts/python
# -*- coding : UTF-8

class Human:

def __init__(self, name):
self.name = name


if __name__ == "__main__":
human01 = Human(name="A")
human02 = Human(name="A")

print(human01 == human02)
print("human 01 : ", human01)
print("human 02 : ", human02)

False
human 01 : <__main__.Human object at 0x000001686E41CC10>
human 02 : <__main__.Human object at 0x000001686E41CE50>

저장되는 장소가 다르기 때문에 다르다.

Bank _ customer ID 확인하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# /c/Users/brill/Desktop/PyThon_Function/venv/Scripts/python
# -*- coding : UTF-8

class Bank:

#instance attribute
def __init__(self, cust_id, balance=0):
self.balance = balance
self.cust_id = cust_id

#instance methode
def withdraw(self, amount):
self.balance -= amount

def __eq__(self, other):
print("__eq()__ is called")
return self.cust_id == other.cust_id

if __name__ == "__main__":
account01 = Bank(123, 1000)
account02 = Bank(123, 1000)
account03 = Bank(456, 1000)
print(account01 == account02)
print(account02 == account03)
print(account01 == account03)

eq() is called
True
eq() is called
False
eq() is called
False



  • 부등호 연산자
    • != : ne()
    • >= : ge()
    • <= : le()
    • > : gt()
    • < : lt()

eq() 함수 사용하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# /c/Users/brill/Desktop/PyThon_Function/venv/Scripts/python
# -*- coding : UTF-8

class Bank:

#instance attribute
def __init__(self, cust_id, balance=0):
self.balance, self.cust_id = balance, cust_id


#instance methode
def withdraw(self, amount):
self.balance -= amount

def __eq__(self, other):
print("__eq()__ is called")
return (self.cust_id == other.cust_id) and (type(self) == type(other))

class Phone:

def __init__(self, cust_id):
self.cust_id = cust_id

def __eq__(self, other):
return self.cust_id == other.cust_id


if __name__ == "__main__":
account01 = Bank(1234)
phone01 = Phone(1234)

print(account01 == phone01)

eq() is called
False

eq를 불러와서 같은지 확인 할 수 있다.

접근기록, log 기록 확인하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# /c/Users/brill/Desktop/PyThon_Function/venv/Scripts/python
# -*- coding : UTF-8


class Bank:
def __init__(self, cust_id, name, balance = 0):
self.cust_id, self.name, self.balance = cust_id, name, balance

def __str__(self):
cust_str = """
customer:
cust_id : {cust_id}
name : {name}
balance : {balance}
""".format(cust_id = self.cust_id, name = self.name, balance= self.balance)

return cust_str

if __name__ == "__main__":
bank_cust = Bank(123, "YH")
print(bank_cust)

  • DB에 저장 되지 않지만, 로그 기록을 확인 할 수 있다.

str() and repr() 비교

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# /c/Users/brill/Desktop/PyThon_Function/venv/Scripts/python
# -*- coding : UTF-8


class Bank:
def __init__(self, cust_id, name, balance = 0):
self.cust_id, self.name, self.balance = cust_id, name, balance

def __str__(self):
cust_str = """
customer:
cust_id : {cust_id}
name : {name}
balance : {balance}
""".format(cust_id = self.cust_id, name = self.name, balance= self.balance)

return cust_str

def __repr__(self):
cust_str = "Bank({cust_id}, '{name}', {balance})".format(cust_id = self.cust_id, name = self.name, balance= self.balance)
return cust_str

if __name__ == "__main__":
bank_cust = Bank(123, "YH")
print(str(bank_cust))
print(repr(bank_cust))

difference of str() and repr()

Making Category

---
title: "Making Category"
excerpt :"Credit card"
classes: wide
categories:
-init
tags:
-python
-title
-coding
last_modified_at: 2021-11-03
---

color 바꾸고 싶은에 안되네

https://www.color-hex.com/color/f4dcdc