'How to use dictionary data initialized in a "class" object
I expose the problem quickly: I have to create 3 classes. X Y and Z, inside X y and z are initialized as variables of class x but not as objects Y and Z. What is the problem: I initialized object Y as requested but I literally don't know how to use the data inside to then develop object Z.
class Network(object) :
def __init__(self,nodes = {},lines = {}):
self._nodes = nodes
self._lines = lines
with open("C:/Users/Willy/Desktop/OVN_LABS/LAB_3/resources/nodes.json") as file_pre:
ne_dict = json.load(file_pre)
for node in ne_dict:
nodes[node] = {Node(node,ne_dict[node]["position"],ne_dict[node]["connected_nodes"])}
@property
def label(self):
return self._label
@property
def position (self):
return self._position
@property
def connected_nodes(self):
return self._connected_nodes
@label.setter
def label(self,label):
self._label = label
@position.setter
def position(self,position):
self._position = position
@connected_nodes.setter
def connected_nodes(self,connected_nodes):
self._connected_nodes = connected_nodes
class Line(object) :
def __init__(self,label="",length=0):
self._label = label
self._length = length
self._successive = {}
@property
def label(self):
return self._label
@label.setter
def label(self,label):
self._label = label
@property
def length(self):
return self._length
@length.setter
def length(self,length):
self._length = length
The json file has this pattern:
{
"A": {
"connected_nodes": [
"B",
"C",
"D"
],
"position": [
-350e3,
150e3
]
},
"B": {
"connected_nodes": [
"A",
"D",
"F"
],
"position": [
-100e3,
400e3
]
},
"C": {
"connected_nodes": [
"A",
"D",
"E"
],
"position": [
-200e3,
-300e3
]
},
"D": {
"connected_nodes": [
"A",
"B",
"C",
"E",
"F"
]
And the request is : Define the class Network that has the attributes: • nodes: dict[Node] • lines: dict[Lines] both the dictionaries have to contain one key for each network element that coincide with the element label. The value of each key has to be an instance of the network element (Node or Line). The constructor of this class has to read the given JSON file ’nodes.json’, it has to create the instances of all the nodes and the lines The line labels have to be the concatenation of the node labels that the line connects (for each couple of connected nodes, there would be two lines, one for each direction, e.g. for the nodes ’A’ and ’B’ there would be line ’AB’ and ’BA’). The lengths of the lines have to be calculated as the minimum distance of the connected nodes using their positions.
The problem is that, not having familiarity with python, I literally do not know how to exploit the creation of the object to get the data I need in the Line class which, for example, serves the length of the line segment which, however, is given by 2 positions that do not I can save.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|