즐거운프로그래밍

[파이썬] 기초 다지기 클래스(class)

수수께끼 고양이 2023. 10. 27. 16:31
728x90
반응형

 

class 정의하기

객체 사용하기 (shell에서 실행하기)

class Student:
    def __init__(inst,name,age,gender):
        inst.name=name
        inst.age=age
        inst.gender=gender
    def info(inst):
        return inst.name,inst.age,inst.gender
student_1=Student('일지매',25,'남자')
student_1.info()

 

 

 


클래스 활용하기 1 (shell에서 실행하기)

class RCCar:
    def __init__(inst):
        inst.dir='stop'
        inst.spd=0
    def go_forward(inst):
        inst.dir='forward'
    def go_backward(inst):
        inst.dir='backward'
    def turn_left(inst):
        inst.dir='left'
    def turn_right(inst):
        inst.dir='right'
    def set_speed(inst,spd):
        inst.spd=spd
    def stop(inst):
        inst.dir='stop'
        inst.spd=0
    def show_state(inst):
        inst.dir,inst.spd
mycar=RCCar()
mycar.go_forward()
mycar.set_speed(30)
mycar.show_state()

 

 

 


클래스 활용하기 2  (shell에서 실행하기)

class Remote:
    def __init__(inst,car):
        inst.car=car
    def go_forward(inst,spd):
        inst.car.go_forward()
        inst.car.set_speed(spd)
    def stop(inst):
        inst.car.stop()
    def show_state(inst):
        inst.car.show_state()
remote=Remote(mycar)
remote.go_forward(30)
remote.show_state()
remote.stop()
remote.show_state()

 

 

 


클래스 활용하기 3

class CoffeeMachine:
    def __init__(inst):
        inst.menu={}
        inst.total_money=0
    def set_menu(inst,**menu):
        inst.menu=menu
    def get_coffee(inst,money_in,coffee_in):
        change,coffee_out=money_in,None
        if coffee_in in inst.menu.keys():
            price=inst.menu[coffee_in]
            if money_in>=price:
                change=money_in-price
                coffee_out=coffee_in
        return change,coffee_out
cm=CoffeeMachine()
menu={
    'americano':1500,
    'caffe latte':2500,
    'espresso':1500
}
cm.set_menu(**menu)
print(cm.menu)
change,coffee=cm.get_coffee(5000,'espresso')
print(change,coffee)

 

 

 

728x90
반응형