Lab 4 of 5
Β·
Semi-Guided
Build a DeviceInventory Class with __iter__
Objective: Create a DeviceInventory class that makes a list of device records iterable as NetworkDevice objects.
Instructions
Create a file called lab4.py. Write a DeviceInventory class that:
- Takes a list of raw dictionaries in
__init__and stores them - Implements
__len__to return the number of records - Implements
__iter__usingyieldβ each iteration yields aNetworkDeviceobject built from the next raw record
Use this raw data:
raw_data = [
{"name": "sw-core-01", "ip": "10.1.1.1", "type": "switch", "site": "HQ", "vlan": 10},
{"name": "sw-access-01", "ip": "10.1.1.2", "type": "switch", "site": "HQ", "vlan": 20},
{"name": "rtr-edge-01", "ip": "10.1.1.254", "type": "router", "site": "HQ", "vlan": 1},
]
Then use the class:
inventory = DeviceInventory(raw_data)
print(f"Loaded {len(inventory)} devices")
for device in inventory:
print(f"{device.name} | {device.ip} | {device.device_type} | VLAN {device.vlan}")
Your output must match exactly:
Loaded 3 devices
sw-core-01 | 10.1.1.1 | switch | VLAN 10
sw-access-01 | 10.1.1.2 | switch | VLAN 20
rtr-edge-01 | 10.1.1.254 | router | VLAN 1
Run it with python3 lab4.py. Paste your output below and submit.
π‘ Show Hint
def __iter__(self): then for record in self._raw: then yield NetworkDevice(record["name"], record["ip"], record["type"], record["site"], record["vlan"]). Include NetworkDevice class at the top of lab4.py β do not import it.
Paste Your Output