Class types

Every class is also a valid type. Any instance of a subclass is alsocompatible with all superclasses – it follows that every value is compatiblewith the object type (and incidentally also the Any type, discussedbelow). Mypy analyzes the bodies of classes to determine which methods andattributes are available in instances. This example uses subclassing:

  1. class A:
  2. def f(self) -> int: # Type of self inferred (A)
  3. return 2
  4.  
  5. class B(A):
  6. def f(self) -> int:
  7. return 3
  8. def g(self) -> int:
  9. return 4
  10.  
  11. def foo(a: A) -> None:
  12. print(a.f()) # 3
  13. a.g() # Error: "A" has no attribute "g"
  14.  
  15. foo(B()) # OK (B is a subclass of A)