# def로 정의한 함수의 예시
def square(x):
return x**2
print(square(3)) # 9가 나옴
# lambda로 정의한 함수의 예시
square = lambda x: x ** 2
print(square(3)) # 출력: 9
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
print(squared) # [1, 4, 9, 16]
nums = [1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even) # [2, 4]
from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(product) # 24 (1*2*3*4)
객체(object) : 객체는 속성과 값을 가진 대상을 의미함
객체지향(object-oriented) 프로그래밍
절차지향 프로그래밍
객체지향 vs 절차지향 프로그래밍
항목 | 객체 지향 (예: Python, C++) | 절차 지향 (예: C) |
---|---|---|
설계 철학 | 데이터+함수를 객체로 묶음 | 함수 중심, 데이터는 따로 |
구조화 방식 | 객체(클래스)를 설계하고 호출 | 로직을 단계별로 나열 |
재사용성 | 클래스(객체) 단위 재사용 | 함수 단위 재사용 |
확장성 | 캡슐화, 상속 등으로 유연함 | 유지보수 어려움 |
예시 | class , object 를 통해 분산 |
int main() 에 모든 흐름 존재 |
객체지향 예시(python)
# Person이라는 class를 정의
# Person에는 name, age 속성이 있음
class Person:
def __init__(self, name, age):
self.name = name # 내부 상태 저장
self.age = age
def print_info(self):
print(f"{self.name} is {self.age} years old") # 자기 데이터 접근
p = Person("슈나우저", 30) # 이름 대신 별명을 넣어봄
p.print_info() # 별도 인자 없이 자기 상태로 처리
# 슈나우저 is 30 years old
void print_person(char name[], int age) {
printf("%s is %d years old\n", name, age);
}
int main() {
char name[] = "슈나우저";
int age = 30;
print_person(name, age); // 직접 값 넘김
}
# 예시-1) 객체를 변수에 직접 저장!
def greet():
return "Hello!"
say_hello = greet # 함수 greet를 변수에 할당
print(say_hello()) # Hello!
def greet():
return "Hi!"
def call_func(func):
print(func()) # 함수 매개변수로 전달 후 호출
call_func(greet) # Hi
def get_multiplier(factor):
def multiply(x):
return x * factor
return multiply # 함수를 리턴값으로 반환
times3 = get_multiplier(3)
print(times3(10)) # 30