Class hint type

class Node:
    def append_child(self, node: Node):
       if node != None:
        self.first_child = node
    self.child_nodes += [node]

How do I do node: Node? Because when I run it, he says name 'Node' is not defined.

Should I just delete : Nodeand instance check it inside the function? But how can I access nodeproperties (which I would expect to be an instance of a class node)?

I do not know how to implement type casting in Python, BTW.

+8
source share
4 answers

"self" type checking references are usually made using strings:

class Node:
    def append_child(self, node: 'Node'):
       if node != None:
        self.first_child = node
    self.child_nodes += [node]

This is described in the Forward Links section of PEP-0484.

, . , python () 1. (, mypy) .

1 - - , , python .

+14

Python 3.7 Python 4.0

Python 3.7, Python PEP 563. PEP 563 __annotations__ . Python 3.7, __future__ __future__:

from __future__ import annotations

:

class C:
    a: C
    def foo(self, b: C):
        ...

Python 4.0, .

+4

, mgilson.

mgilson answer , Python. , , , .

Python . Python , "". Python, - . Python (, ), . def foo(args): code - , foo. , class Bar(bases): code , ( , , , , , def), Bar. , . , , . , , , , .

(, , , . , - , Python , , , . , ( , , class Bar: pass, def method1():...; Bar.method1 = method1 ..), , Python .)

:

class C:
    C  # NameError: C doesn't exist yet.
    def method(self):
        return C  # This is fine.  By the time the method gets called, C will exist.
C  # This is fine; the class has been created by the time we hit this line.
+1

Python> 3.7 . .

In this specific example, Node refers to itself, and you will receive, and if you run it, you will receive

NameError: name 'Node' is not defined

To overcome this error, you must include:

from __future__ import annotations

This should be the first line in the module. In Python 4.0 and above you do not need to includeannotations

from __future__ import annotations
from dataclasses import dataclass

@dataclass
class Node:
    value: int
    left: Node
    right: Node

    @property
    def is_leaf(self) -> bool:
        """Check if node is a leaf"""
        return not self.left and not self.right

Example:

node5 = Node(5, None, None)
node25 = Node(25, None, None)
node40 = Node(40, None, None)
node10 = Node(10, None, None)

# balanced tree
node30 = Node(30, node25, node40)
root = Node(20, node10, node30)

# unbalanced tree
node30 = Node(30, node5, node40)
root = Node(20, node10, node30)
+1
source

Source: https://habr.com/ru/post/1663700/


All Articles