콜백에서 컴포지션으로
Coddy의 C 개발자를 위한 Python 코스 레슨. 48개 중 38번째.
C 구조체는 함수 포인터를 동작 슬롯으로 담을 수 있으며, 필요에 따라 컨텍스트 포인터와 짝지을 수 있습니다. Python의 컴포지션은 협력 객체를 저장하고 해당 객체의 메서드를 호출합니다. Bill은 가격 계산식을 복사하거나 대체 객체를 새로 만드는 대신 현재 정책에 작업을 위임해야 합니다. 이렇게 하면 호출자가 동일한 청구서를 유지하면서 협력 객체를 교체할 수 있습니다. 객체가 이미 소비자에게 필요한 메서드를 제공한다면 공통 기본 클래스는 필요하지 않습니다.
C: example.c 완성하기
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
struct Policy { int (*cost)(int); };
int double_cost(int units) { return units * 2; }
int bill(const struct Policy *p, int units) { return p->cost(units); }
int main(void) {
struct Policy p = {double_cost};
printf("%d\n", bill(&p, 4));
return 0;
}Python: example.py 완성하기
class DoublePolicy:
def cost(self, units):
return units * 2
class Bill:
def __init__(self, policy):
self.policy = policy
def total(self, units):
return self.policy.cost(units)
print(Bill(DoublePolicy()).total(4))차이점 살펴보기
계약상 협력 객체 전체를 교체할 수 있다면 초기 메서드를 캐싱하지 마세요. total이 실행될 때 self.policy.cost를 읽으면 현재 정책을 사용하게 됩니다. Python이 메모리 할당을 관리하더라도 소유권과 변경은 여전히 중요합니다.
코드는 rate.py, usage_bill.py에 작성하세요. 잠겨 있는 driver.py는 진입 파일로, 실행과 검사를 제공하며 편집할 수 없습니다.
챌린지
초급곱셈을 사용해 Rate(cents).cost(units)를 구현하고, 저장된 현재 요금의 cost(units)에 위임해 UsageBill(rate).total(units)를 구현하세요. 드라이버는 요금, 사용량, 대체 요금, 보너스(음이 아닌 정수)를 읽고, 첫 번째 합계를 출력한 다음, replacement_rate * units + bonus를 계산하는 객체로 협력 객체를 교체하고 다시 출력합니다.
편집 가능한 모듈에 지정된 정의를 구현하되 입력을 받거나 출력하지 마세요. 드라이버가 입력과 출력을 담당하며, 추가 출력을 생성하지 않고 새 데이터로 API를 다시 호출할 수 있습니다.
C 설계에서 구현을 하드 코딩하는 대신 제공된 동작 슬롯을 호출하는 것처럼, 현재 협력 객체에 위임하세요.
코드는 rate.py, usage_bill.py에 작성하세요. 잠긴 driver.py는 진입 파일이며, 실행과 검사를 담당하므로 편집할 수 없습니다.
직접 해보기
from rate import Rate
from usage_bill import UsageBill
class BonusRate:
def __init__(self, cents, bonus):
self.cents = cents
self.bonus = bonus
def cost(self, units):
return self.cents * units + self.bonus
cents, units, replacement, bonus = [int(input()) for _ in range(4)]
bill = UsageBill(Rate(cents))
print(bill.total(units))
bill.rate = BonusRate(replacement, bonus)
print(bill.total(units))
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 Python의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러