from dataclasses import dataclass
@dataclass
class InventoryItem:
name: str
price: int
quantity: int = 1
def cost(self) -> float:
return self.price * self.quantity
InventoryItem(name='django', price=200)
InventoryItem(name='django', price=200, quantity=1)
item = InventoryItem(name='django', price=200, quantity=2)
item.cost()
400
try:
InventoryItem(name=300, price=200, quantity=2)
except Exception as E:
print(E)
InventoryItem
__main__.InventoryItem
from typing import List
nums: List[int] = [1,2,3]
try:
nums.append('Python')
except Exception as E:
print(E)
nums.append(1)
nums
[1, 2, 3, 'Python', 1]
try:
nums['append'] = 'Python'
except Exception as E:
print(E)
list indices must be integers or slices, not str
from typing import Dict
countries: Dict[str, str] = {"KR": "South Korea", "US": "United States", "CN": "China"}
countries
{'KR': 'South Korea', 'US': 'United States', 'CN': 'China'}
from typing import Final
TIME_OUT: Final[int] = 10
TIME_OUT
10
from typing import Tuple
user: Tuple[int, str, bool] = (3, "Dale", True)
user
(3, 'Dale', True)
from typing import Set
chars: Set[str] = {"A", "B", "C"}
chars
{'A', 'B', 'C'}
from typing import Union
def toString(num: Union[int, float]) -> str:
return str(num)
from typing import Callable
def repeat(greet: Callable[[str], str], name: str, times: int = 2) -> None:
for _ in range(times):
print(greet(name))
# InLine 방식으로 타입 선언함수를 객체 설정에 적용
greet: Callable[[str], str] = lambda name: f"Hi, {name}!"
repeat(greet, "Dale")
Hi, Dale! Hi, Dale!
from typing import Iterable, List
def toStrings(nums: Iterable[int]) -> List[str]:
return [str(x) for x in nums]
# InLine 방식으로 타입 선언함수를 객체 설정에 적용
greet: Callable[[str], str] = lambda name: f"Hi, {name}!"
repeat(greet, "Dale")
Hi, Dale! Hi, Dale!
import dataclasses
import pydantic
@dataclasses.dataclass
class Z:
z: int
@dataclasses.dataclass
class Y(Z):
y: int = 0
@pydantic.dataclasses.dataclass
class X(Y):
x: int = 0
foo = X(x=b'1', y='2', z='3')
foo
_Pydantic_X_49892560(z=3, y=2, x=1)
try:
X(z='python')
except pydantic.ValidationError as E:
print(E)
1 validation error for X z value is not a valid integer (type=type_error.integer)