将属性的类型信息构建到超类中以进行类型提示

时间:2018-01-27 22:07:11

标签: python type-hinting mypy

所以我有几个共享共同属性的类

class Person(object):
    def __init__(self, name, age, income):
        self.name = name
        self.age = age
        self.income = income

class Pet(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

我想为这些对象创建一个超类

class Animal(object):
    ...

因此我可以在函数中引用此类型并从IDE获取类型提示

def f(x: Animal):
    x.name<tab>  # I expect to see that this thing is a string type

或者从像mypy这样的项目中获得很好的静态分析。

为了实现这种行为,我编写课程的最佳方式是什么?

1 个答案:

答案 0 :(得分:3)

从Python 3.6开始,您可以使用variable annotations

class Animal(object):
    name: str
    age: int
    income: int

这些不是类属性;它们指定实例属性的类型。

来自specification

  

类型注释还可用于在类主体和方法中注释类和实例变量。特别是,无值符号a:int允许用户注释应该在__init____new__中初始化的实例变量。

相关问题