0
点赞
收藏
分享

微信扫一扫

阅读Faker源码时遇到的奇怪代码


from typing import Any, Callable, Dict, Hashable, List, Optional, Pattern, Sequence, Tuple, Union

class Faker:
    """Proxy class capable of supporting multiple locales"""
    # 代理类,支持多个地区(语言环境)
    cache_pattern: Pattern = re.compile(r"^_cached_\w*_mapping$") # 正则语法
    generator_attrs = [
        attr for attr in dir(Generator) if not attr.startswith("__") and attr not in ["seed", "seed_instance", "random"]
    ]

    def __init__(
        self,
        locale: Optional[Union[str, Sequence[str], Dict[str, Union[int, float]]]] = None,
        providers: Optional[List[str]] = None,
        generator: Optional[Generator] = None,
        includes: Optional[List[str]] = None,
        use_weighting: bool = True,
        **config: Any,
    ) -> None:

上面是关于Faker类的定义,部分代码.

其中,有一些地方的代码非常特殊...

cache_pattern: Pattern = re.compile(r"^_cached_\w*_mapping$")

# 这里,使用[: Pattern] 表示cache_pattern的类型是一个Pattern
: Pattern 可以省略,也可以换成其他的.

例如:
a: str = "123"


在python中,使用: <type>指定变量类型,这种编程不止在函数传参时适用.
在定义变量时也适用.

def __init__(self,...) -> None:
    pass


这里的->None,可以省略.但是就像前面的: <type>一样
这里的-> <type> 也是起到了[指示返回数据类型]的作用.

举报

相关推荐

0 条评论