Skip to Content
전문가를 위한 파이썬(2판)
book

전문가를 위한 파이썬(2판)

by 루시아누 하말류, 강권학
November 2024
Beginner to intermediate
1064 pages
25h 21m
Korean
Hanbit Media, Inc.
Content preview from 전문가를 위한 파이썬(2판)
633
15
자료형 힌트 조금 더 알아보기
15
.
8
제네릭 정적 프로토콜의 구현
파이썬
3
.
10
표준 라이브러리에서는 몇 가지 제네릭 정적 프로토콜을 제공한다. 그중 하나가
SupportsAbs
인데,
typing
모듈에 다음과 같이 구현되었다 (
https://fpy.li/15-34
).
@runtime_checkable
class SupportsAbs(Protocol[T_co]):
“””반환형에 있어서 공변적인 __abs__() 추상 메서드 하나가 있는 ABC”””
__slots__ = ()
@abstractmethod
def __abs__(self) -> T_co:
pass
T_co
는 명명 관례에 따라 다음과 같이 선언되었다.
T_co = TypeVar(‘T_co’, covariant=True)
[예제
15
-
21
]에서 보듯이,
SupportsAbs
덕분에
Mypy
는 이 코드가 올바르다고 판단한다.
예제
15-21
abs
_
demo
.
py
: 제네릭
SupportsAbs
프로토콜의 사용
import math
from typing import NamedTuple, SupportsAbs
class Vector2d(NamedTuple):
x: float
y: float
def __abs__(self) -> float: ❶
return math.hypot(self.x, self.y) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

전문가를 위한 리액트

전문가를 위한 리액트

테자스 쿠마르
고성능 파이썬(2판)

고성능 파이썬(2판)

오현석, 미샤 고렐릭, 이안 오스발트

Publisher Resources

ISBN: 9791169211772