在python中键入提示私有属性的正确方法

jam*_*nco 6 python properties type-hinting python-3.x

在 PEP 526 之后,我想知道如何正确键入提示由属性修饰的实例或类属性。我是否键入提示基础属性或名称或属性?

键入属性的示例:

class Sample(object):
    _target_dir: Path

    @property
    def target_dir(self):
        pass
Run Code Online (Sandbox Code Playgroud)

或者输入属性:

class Sample(object):
    target_dir: Path
Run Code Online (Sandbox Code Playgroud)

还是其他方式?实例变量和类变量是否相同?

Mic*_*x2a 7

您应该装饰该@property属性所包装的底层函数:

class Sample:
    @property
    def target_dir(self) -> Path:
        return Path("/foo/bar")
Run Code Online (Sandbox Code Playgroud)

如果您的属性围绕某些底层私有属性,则由您决定是否要对其进行注释。我建议您这样做,这样无论您在哪里使用该私有属性,都可以从类型检查中受益,但是您添加的任何类型都将与属性本身的类型无关。