인터페이스 필드와 호출
Coddy의 Go 개발자를 위한 Python 코스 레슨. 48개 중 38번째.
Go의 구조체는 인터페이스 타입의 협력 객체를 저장할 수 있어 구현을 다양하게 바꿀 수 있습니다. Python 객체는 협력 객체를 저장하고 인터페이스 필드 타입을 선언하지 않아도 필요한 메서드를 호출할 수 있습니다. 청구서가 처리 흐름을 담당하고 요율이 가격 책정을 담당합니다. 매번 현재 협력 객체를 조회하면 교체한 객체가 이후 호출에 반영됩니다. 청구서에 계산식을 복사하면 이러한 분리가 깨지고, 낯설지만 호환되는 정책을 사용할 수 없게 됩니다.
Go
Go 코드 발췌: 선언은 main 위에, 문장은 main 안에 있습니다. 가져오기 항목: fmt. 검증 묶음에 전체 프로그램이 들어 있습니다.
type Pricer interface { Cost(int) int }
type Rate struct { Cents int }
func (r Rate) Cost(units int) int { return r.Cents * units }
type Bill struct { Rate Pricer }
func (b Bill) Total(units int) int { return b.Rate.Cost(units) }
// main 내부:
b := Bill{Rate: Rate{Cents: 4}}
fmt.Println(b.Total(3))
b.Rate = Rate{Cents: 7}
fmt.Println(b.Total(3))Python
class Rate:
def __init__(self, cents):
self.cents = cents
def cost(self, units):
return self.cents * units
class Bill:
def __init__(self, rate):
self.rate = rate
def total(self, units):
return self.rate.cost(units)
b = Bill(Rate(4))
print(b.total(3))
b.rate = Rate(7)
print(b.total(3))이식 시 주의점
계약에서 cost(units)만 요구한다면 특정 클래스 이름을 요구하지 마세요. Python 타입 힌트로 프로토콜을 설명할 수 있지만, 일반적인 덕 타이핑 호출은 공통 기반 클래스 없이도 작동합니다.
챌린지
초급Rate(cents).cost(units)는 곱셈으로 구현하고, UsageBill(rate).total(units)는 저장된 현재 요금의 cost(units)에 위임하세요. 드라이버는 요금, 사용량, 대체 요금, 보너스(0 이상의 정수)를 읽고, 첫 번째 합계를 출력한 다음, replacement_rate * units + bonus를 계산하는 객체로 협력 객체를 교체하고 다시 출력합니다. Go의 인터페이스 타입 필드와 마찬가지로, 수식을 복사하는 대신 현재 협력 객체에 위임하세요.
수정 가능한 파일: rate.py, usage_bill.py. 제공된 import 문과 필수 API 이름은 그대로 두세요. 잠금된 driver.py가 실행과 검사를 담당하므로 수정하지 마세요.
수정 가능한 모듈에 이름이 지정된 정의를 입력이나 출력 없이 구현하세요. 드라이버가 입력과 출력을 담당하며, 추가 출력을 생성하지 않고 새 데이터로 API를 다시 호출할 수 있습니다.
직접 해보기
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))
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Go 개발자를 위한 Python의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러