Day11

Ju-Young Han·2024년 1월 20일

python

목록 보기
19/22

#정삼각형, 정사각형 넓이 구하라.
class triangle:
def init(self,b,h):
self.base = b
self.height = h
def get_area(self):
return self.base self.height 0.5
def get_round(self):
return self.base *3

class square:
def init(self,s):
self.side = s
def get_area(self):
return self.side * self.side

#객체의 개념
객체란: 객체는 속성(변수)과 메서드(함수)를 하나의 단위로 묶은 것.
속성: 속성은 객체의 특징을 나타냅니다.예를 들어 자동차의 색상 (빨강, 파랑), 브랜드, 연식, 등이 속성에 속한다.
메서드: 자동차가 운전하기, 정지하기 듣ㅇ등의 기능을 수행하는 것이 메서드에 해당한다.

#클래스: 객체 지향 프로그램
1. 클래스 선언
2. 속성(멤버변수: attributes): 클래스에 소간 데이터.
3. 메서드(method) 동작이나 행위
4. 생성자(init 메서드): 생성자는 클래스의 인스턴스가 생성될 때 자동으로 호출되는 특별한 메서드 이다. 이 메서드는 주로 해당 객체의 초기 상태를 성절하는데 사용.

class Account:
def init(self,a,b,c):
self.number = a
self.owner = b
self.balance= c

def depoist(self, money):
    self.balance += money
    print('입금이 되었습니다.')
    
def withdraw(selfself, money):
    if(self.balance < money):
        print('잔고가 부족합니다')
    else:
        self.balance -= money
        print('출금이 되었습니다')
def checkBalnce(self):
    print(f"잔액은 {self.balance}  남았습니다.")

han = Account(100, 'han', 100000)
han.deposit(50000)
han.checkBalance()
han.withdraw(500000)
han.withdraw(30000)
han.checkBalance()

##쇼핑카트 시스템_속성: 상품목록, 총금액, 메서드: 상품추가하기, 상품삭제
class Cart:
def init(self):
self.itemList = []
self.total = 0

def additem(self, item):
    self.itemList.append(item)
    print(f"{item.name} 이 추가 되었습니다.")
    self.itemList.append(item)
def removeItem(self):
    for index, item in enumerate(self.itemList):
        print(f"{index.{item}")
    num = int(input("삭제할 상품의 번호를 선택하세요:"))
    self.itemList.pop(num)
    print("삭제 되었습니다.")
def totalAmount(self):
    total = 0
    for i in self.itemList:
        total = i['price']
    print(f"총 금액은 {total}입니다.")

myCart = Cart()
myCart.addItem({'name': '샴푸','price':'5000'})
myCart.addItem({'name': '린스', 'price': '10000'})
myCart.addItem({'name': '트리트먼트', 'price': '8000'})
myCart.addItem({'name': '에센스', 'price': '7000'})
myCart.removeItem()
myCart.totalAmount()

inheritance(상속)

객체 지향 프로그래밍 중에서 중요한 개념. 상속을 통해 한 클래가 다른 클래스의 속성과
매서드를 그대로 이어 받을 수 있다. 코드 재사용을 높이고, 중복을 줄여 구조를 효율적이게 한다.

class Shape:
def get_area(self):
pass
def get_round(self):
pass

class Animal:
def init(self, b, g):
self.breed = b
self.gender = g
def running(self):
print('신나게 달립니다')
class Dog(Animal):
def init(self, b, g, body):
super().init(b,g)
self.body = body
def bark(self):
print('멍멍')
class Cat(Animal):
def init(self, b, g, eyes):
super().init(b,g)
self.eyes = eyes
def crying(self):
print('냐옹')
kingyul = Dog('이탈리안 하우즈', 'female', 'white')
samseki = cat('치즈냥이','male','blue')

kingyul.bark()
kingyul.running()
samseki.crying()
samseki.running()

#오버라이딩(overriding): 자식 클래스가 부모 클래서로부터 상속받은 메소드를 자신의 필요에 맞게 재 정의 하는 것을 의미.
특징
재정의: 부모클랫의 메서드와 동일한 이름. 매개변수로 자식 클래스에서 메서드를 재정의 한다.
확장: 부모 클래스의 기능을 유지하면서 추가적인 기능을 더할 수 있다.
다형성: 같은 메서드 이름으로 다양한 기능을 구현 할 수 있어, 다형성을 실현하는데 중요한 역할을 한다.

iphoneList = ['iphone13','iphone14','iphone15']
iphonePriceList = [10,20,30]
#zip(지퍼)
print(list(zip(iphoneList,iphonePriceList)))

#iphoneList = ['iphone13','iphone14','iphone15']
#iphonePriceList = [10,20,30]
#zip(지퍼)
#print(list(zip(iphoneList,iphonePriceList)))

#print([{'아이폰':phone,'가격': price} for phone, price in zip(iphoneList, iphonePriceList}])

alpha = ['a','b','c','d','e']
number = [1,2,3,4,5]

print([{'알파벳':a,'순서':n} for a,n in zip(alpha,number) ])

text = "apple banana apple strawberry banna"
wordList = text.split()
wordLenList = list(map(lambda x:len(x), wordList))
print([{'단어':word,'글자 수':length} for word, length in zip(wordList,wordLenList)])

0개의 댓글