[udemy] python 부트캠프_section 19_인스턴스, 상태 및 고차함수

Dreamer ·2022년 9월 11일
0
post-thumbnail

01. 고차함수

  • 고차함수란 다른 함수와 함께 작동하는 함수를 의미한다.
  • 아래의 예에서, calculator() 함수는 고차함수이다. 다른 함수를 input 값으로 사용하기 때문이다.
# 고차함수
# Functions as Inputs

def function_a(something):
    # Do this with something
    # Then do this
    # Finally do this
    
def function_b():
    # Do this

function_a(function_b)

# example 
def add(n1,n2):
    return n1 + n2

def subtract(n1,n2):
    return n1 - n2

def multiply(n1, n2):
    return n1 * n2

def divide(n1,n2):
    return n1 / n2

def calculator(n1,n2,func):
    return func(n1,n2)


result = calculator(2,3,divide)
print(result)

02. 객체 상태 및 인스턴스

timmy = Turtle()
tommy = Turtle()

timmy.color = green
tommy.color = purple
  • timmy, tommy는 Turtle 객체의 하나의 예가 된다.
  • 이 둘은 서로 다른 속성을 지닐 수 있고, 다른 동작을 수행할 수 있다.
  • timmy, tommy를 instance라 한다.
  • 각 객체가 어느 한 순간에 각기 다른 속성을 지닐 수 있으며, 각기 다른 메소드를 수행할 수 있다는 사실을 객체의 상태(state)라고 한다.

03. quiz_turtle

from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(width= 500, height= 400)
user_bet = screen.textinput(title= "Make your bet",
                            prompt= "Which turtle will win the race? Enter a color: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
y_positions = [-70,-40,-10,20,50,80]
all_turtles = []

for turtle_index in  range(len(colors)):
    new_turtle = Turtle(shape="turtle")
    new_turtle.penup()
    new_turtle.goto(x= -230, y=y_positions[turtle_index])
    new_turtle.color(colors[turtle_index])
    all_turtles.append(new_turtle)

if user_bet:
    is_race_on = True

while is_race_on:
    for turtle in all_turtles:
        if turtle.xcor() > 230:
            is_race_on = False
            winning_color = turtle.pencolor()
            if winning_color == user_bet:
                print("You've won!")
            else:
                print("You've lost!")
        rand_distance = random.randint(0,10)
        turtle.forward(rand_distance)

screen.exitonclick()
profile
To be a changer who can overturn world

0개의 댓글