How to pass to class method argument of class type in python?

Viewed 41

I have a class and would like to define a method that accepts an argument of the same class type like this:

class MyClass:

  def my_method(self, param: MyClass):
    pass

But I have an error Unresolved reference 'MyClass'

How to solve this issue?

1 Answers

From the docs:

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

So you can put your class name inside the quotes:

class MyClass:
  def my_method(self, param: 'MyClass'):
    pass
Related