본문 바로가기

웹_프론트_백엔드/Python

2020.01.29

1. lex01_class.py

# -*- coding: utf-8 -*-
# cafe management 
# 클래스 이름 : Event
# 추상화 :클래스 만들기
# 주문서 추상화
# 속성 (인스턴스 변수)
#1. 주문번호 : 번호(숫자).고유한 숫자(id)
#2. 주문내용 :아메리카노 3잔, 라떼 1잔, 딕셔너리로. 
# 메서드
#1. 생성 (__init__())
#2. 주문 (order() )
#3. 주문금액계산 (calculate() )
#4. 출력(print())

menu_table = {'americano': 3000, 'latte': 6000, 'icecream': 3000}
print(type(menu_table))

#클래스 만들기
class Event():
    def __init__(self, number):
        #속성 만들기 (property): init()에서 만들기 (초기화)
        self.id = number
        self.order_list = {}
        self.total=0
    def order (self, menu) :
        #print(menu)
        self.order_list =menu
    def print(self):
        print('주문번호:', self.id)
        for key, value in self.order_list.items(): 
            print('{0:10} {1:5} {2:5} {3:5}'.format(key, value,menu_table[key], value*menu_table[key]))
        print(self.total)
    def calculate(self) :
        total =0
        for key, value in self.order_list.items(): 
            #print(key, value, menu_table[key], value*menu_table[key])
            total +=  value*menu_table[key]
        self.total = total
        return total
event_list= [
{'americano':2, 'latte':1},
{'latte':1, 'americano':3,'icecream':1},
{'americano':3,'icecream':1},
{'latte':1, 'icecream':1}, ]

# 객체 만들기
# 총매출 구하기, 주문번호는 1씩 증가
total =0
for i, ev in enumerate(event_list, 1):
    event = Event(i)
    event.order(ev)
    total += event.calculate()
    event.print()
print('총매출은 :', total ) 

2. lec02_inheritance.py

# -*- coding: utf-8 -*-
#  상속  inheritance
#  상속을 사용하는 이유(이점)
#  기존 클래스에 일부 내용 추가/변경을 통하여 새클래스를 생성. 코드의 재사용(reuse)
#  기존 클래스를 복사하지않고(손으로) 기존클래스 복사의 효과를 누릴 수 있음. 
#  기존 클래스의 모든 코드를 사용할 수 있음. 

# 기존클래스 : 부모클래스, 슈퍼클래스, 베이스클래스, parent, super, base
# 새클래스 : 자식클래스, 서브클래스, 파생된클래스, chile, sub, derived

# 오버라이드 overrider (재정의) : 기존클래스의 내용을 추가/변경
# OOP(Object Oriented Programming)객체지향프로그래밍(언어) : 
# 추상화(클래스 만드는 것)/다형성(오버라이드)/상속/은닉(Encapsulation)

#부모 클래스 : 속성변수 이름(name), 메서드 인사(greetings()-안녕하세요 출력)
class Person():
    #생성자 (객체가 생성될 때 자동으로 호출)
    def __init__(self, name) :
        #property (멤버변수(인스턴스 변수))
        self.name = name
    def greetings(self) :
        print("안녕하세요")
    def info(self) :
        print(self.name)

#자식 클래스 : 이름은 상속받고 나이를 추가. 
class Child(Person) :
    # name이 없지만 부모에게 있기 때문에 있는것과 동일한 효과. 복사 
    def __init__(self, name, age) :
        super().__init__(name)
        self.age= age
    def greetings(self) :
        super().greetings() #super(): 부모클래스에 있는 메서드를 부름
        print("안녕")
    def run(self) :
        print("뛰어갑니다")
    def info(self) :
        #print(self.name, self.age )
        super().info()
        print(self.age)

        
#객체 생성하기
person = Person("신상림")
person.info()
#메서드 부르기 
person.greetings()
child = Child("김미미",3)
print(child.name)
child.greetings()
child.info()

'웹_프론트_백엔드 > Python' 카테고리의 다른 글

2020.01.31  (0) 2020.02.03
2020.01.30  (0) 2020.01.30
2020.01.28  (0) 2020.01.28
2020.01.23  (0) 2020.01.23
2020.01.22  (0) 2020.01.22