Reputation: 57271
So I have a couple classes that share common attributes
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
I want to make a superclass for these objects
class Animal(object):
...
So that I can refer to this type in functions and get type hints from my IDE
def f(x: Animal):
x.name<tab> # I expect to see that this thing is a string type
Or have nice static analysis from projects like mypy.
What is the best way for me to write my classes to achieve this behavior?
Upvotes: 0
Views: 124
Reputation: 1121864
As of Python 3.6 you can use variable annotations:
class Animal(object):
name: str
age: int
income: int
These are not class attributes; they specify the types for instance attributes.
From the specification:
Type annotations can also be used to annotate class and instance variables in class bodies and methods. In particular, the value-less notation a: int allows one to annotate instance variables that should be initialized in
__init__
or__new__
.
Upvotes: 3