Reputation: 53
I am from java background, learning python. I am trying to create a python class (with static typing), containing a member of same class.
mynode.py
class MyNode():
def __init__(self, id: str=None, child_node: MyNode=None):
self._id = id
self._child_node = child_node
main.py
import mynode
def main():
n1 = MyNode('child1')
if __name__ == '__main__':
main()
But the following errors are occurring while executing. How can this be resolved ?
...\py-tests>python main.py
Traceback (most recent call last):
File "main.py", line 1, in <module>
import mynode
File "...\py-tests\mynode.py", line 1, in <module>
class MyNode():
File "...\py-tests\mynode.py", line 2, in MyNode
def __init__(self, id: str=None, child_node: MyNode=None):
NameError: name 'MyNode' is not defined
Upvotes: 2
Views: 56
Reputation: 531165
At the time __init__
is being defined, the class itself isn't yet defined, let alone bound to a name. Use a forward reference instead, consisting of a string literal.
class MyNode:
def __init__(self, id: str = None, child_node: 'MyNode' = None):
Upvotes: 2