0

I got 2 instances interact with each other, describe in class like

class Fraction:

  def __init__(self, top, bottom):
    self.num = top
    self.den = bottom

  def add(self, B: Fraction):
    # do add two fractions

This causes NameError: name 'Fraction' is not defined in line def add(self, B: Fraction):. I want to catch their type before passing to function like def add(self, B: int): in Python 3.7 or newer

I know that just ignore the type of B or catch type error inside function but is there a better way to do this?

  • 2
    Does this answer your question? [How do I type hint a method with the type of the enclosing class?](https://stackoverflow.com/questions/33533148/how-do-i-type-hint-a-method-with-the-type-of-the-enclosing-class) – Kirk Dec 11 '20 at 16:08
  • I would recommend something like `Union[Fraction, int, float]`, as it would make sense to allow something like `Fraction(3,4) + 1` to evaluate to `Fraction(7, 4)`. – chepner Dec 11 '20 at 16:15
  • Thanks. I have solved my problem – henryangminh Dec 11 '20 at 17:01

0 Answers0