1

I am new to python and I have been practicing it lately. I am trying a make a class Rectangle, and I am trying to write a method that use the class itself as an input.

Here is the pseudo code of a class I am trying to create.

class Crect(): #class rectangle that contains coordinate information to create a rectangle.
    def __init__ ...
    def IsOverlapped(self, rectToCompare: Crect) #compares if two Crect objects are overlapped or not

result: NameError: name 'Crect' is not defined.

I am sure if I don't use the 'Type Hint', the above code would work without any problem. However, I think it is a good habit to use Type Hint, so I was wondering if there is a way to use a class object as an input of a method while using a Type Hint.

falsetru
  • 357,413
  • 63
  • 732
  • 636
Jun Lee
  • 45
  • 7

1 Answers1

4

If you are using Python >= 3.7, to use forward reference, you need to enable Postponed Evaluation of Annotations by importing annotations from __future__.

from __future__ import annotations  # <---

class Crect:
    def __init__(self, ...): ...

    def IsOverlapped(self, rectToCompare: Crect): ...

If you are using Python <= 3.6, you can use string literal:

class Crect:
    def __init__(self, ...): ...

    def IsOverlapped(self, rectToCompare: 'Crect'): ...
falsetru
  • 357,413
  • 63
  • 732
  • 636