I'm studying Python and have an exercise about classes Python. According to the exercise, I have to implement a class of Node, that initialize 2 attribute name
and neighbors
which satisfy the condition:
def test_node(self):
node = Node(name="a", neighbors=[Node(name="b")])
assert node
assert getattr(node, "name") == "a"
assert len(getattr(node, "neighbors")) == 1
But I have trouble to understand the attribute neighbors
in the line node = Node(name="a", neighbors=[Node(name="b")])
. Could someone explain to me?
CodePudding user response:
Regarding your question "What does node = Node(name="a", neighbors=[Node(name="b")])
do?":
Node (name="a")
orNode (name="b")
create an instance ofclass Node
with the respective names.neighbors=[Node(name="b")]
creates alist
, containing an instance ofNode
with the nameb
. As this is passed to the creation of an instance ofNode
with the name a, in total you will get two instances (one with namea
, which has a neighbor in a list namedb
as well as an instance ofNode
named b, without a neighbor).
I hope that clarifies your actual question.
CodePudding user response:
Here is a little demonstration that might be of help:
def test_node():
node = Node(name="a", neighbors=[Node(name="b")])
assert node
assert getattr(node, "name") == "a"
assert len(getattr(node, "neighbors")) == 1
class Node():
def __init__(self, name, neighbors=[]):
self.name = name
self.neighbors = neighbors
def add_neighbor(self, neighbor):
self.neighbors.append(neighbor)
test_node() # No error means passes all checks
# Demonstration
a = Node(name='a') # create node a having name 'a' without any neighbors
b = Node(name='b') # same as above
c = Node(name='c', neighbors=[a,b]) # This node c has a and b as neighbors
print(a.__dict__) # see all node's attributes and their current values
a.add_neighbor(b)
a.add_neighbor(Node(name='d')) # create a node d and add as a neighbor to a
print(a.__dict__) # now a has b and d as neighbors
Run this code and tinker with it to get a better understanding. I'm leaving the type checking as an exercise, as it will be needed to ensure that neighbors are all also of the Node class.
CodePudding user response:
In your implementation, neighbours
is a list composed of str
variables which correspond to the names of the neighbour Nodes
. However, question asks you to create a list of Nodes
that are the neighbours of our Node. That is to say, you have to put the Node
objects themselves to your list, not their names.
Apparently, Node(name="b")
is creating a new Node object with the given name
. What you have to do is to create a constructor that takes a name
parameter and also a list of neighbours (optionally). If list is not provided, then we should understand that that specific Node
doesn't have any neighbours.
One way to do it:
from typing import List, Optional
class Node:
def __init__(self, name, neighbors: "Optional[List[Node]]" = None):
self.neighbors = neighbors if neighbors is not None else []
self.name = name
def add_neighbor(self, node: "Node"):
self.neigbors.append(node)
return self.neighbors
def __str__(self):
return "Node object named as '{}'".format(self.name)
def test_node():
node = Node(name="a", neighbors=[Node(name="b")])
print(node)
print(getattr(node, "name") == "a")
print(len(getattr(node, "neighbors")) == 1)
test_node()
Output:
Node object named as 'a'
True
True