pydantic 拆包解包

2021-02-22  本文已影响0人  hehehehe
一个星号可作用于所有的可迭代对象,称为迭代器解包操作,作为位置参数
传递给函数,两个星号只能作用于字典对象,称之为字典解包操作,作为关
键字参数传递给函数。使用 *和 ** 的解包的好处是能节省代码量

打包 tuple

def pack(a, *b):
        print type(a), a
        print type(b), b
 
pack(1, 2, 3, 4, 5)
<type 'int'> 1
<type 'tuple'> (2, 3, 4, 5)

打包 dict

def pack(a, **b):
        print type(a), a
        print type(b), b
 
pack(1, a1=2, a2=3)
<type 'int'> 1
<type 'dict'> {'a1': 2, 'a2': 3}

解包

def pack(a, b, *c):
        print type(a), a
        print type(b), b
        print type(c), c
 
score = [1.0, 2.0, 3.0, 4.0]
pack(*score)

<type 'float'> 1.0
<type 'float'> 2.0
<type 'tuple'> (3.0, 4.0)

def pack(*c):
        print type(c), c
 
student = {'score' : 1.0, 'id' : 2, 'name' : 'xiaoxiao'}
pack(*student)

<type 'tuple'> ('score', 'id', 'name')

def pack(*a, **b):
        print type(a), a
        print type(b), b
 
age = [1, 2, 3]
student = {'score' : 1.0, 'id' : 2, 'name' : 'xiaoxiao'}
pack(*age, **student)

<type 'tuple'> (1, 2, 3)
<type 'dict'> {'score': 1.0, 'id': 2, 'name': 'xiaoxiao'}
from pydantic import BaseModel
from typing import Dict, List, Sequence, Set, Tuple

class Demo(BaseModel):
    a: int # 整型
    b: float # 浮点型
    c: str # 字符串
    d: bool # 布尔型
    e: List[int] # 整型列表
    f: Dict[str, int] # 字典型,key为str,value为int
    g: Set[int] # 集合
    h: Tuple[str, int] # 元组
from typing import Union
from pydantic import BaseModel

class Time(BaseModel):
    time: Union[int, str]
        
t = Time(time=12345)
print(t.json()) # {"time": 12345}
t = Time(time = "2020-7-29")
print(t.json()) # {"time": "2020-7-29"}

可选数据类型

from typing import Optional
from pydantic import BaseModel

class Person(BaseModel):
    name: str
    age: Optional[int]
上一篇下一篇

猜你喜欢

热点阅读