[Tutor] Format problem
P L
la_spirou at hotmail.com
Mon Oct 19 19:56:45 EDT 2020
Hello, I'm currently doing the Google Coursera python program and I have a question in regard to the code below. I'm not sure why the __str__(self) is not working as intended. All my outputs are not at the nearest hundredth. Thanks for your time.
import random
class Server:
def __init__(self):
"""Creates a new server instance, with no active connections."""
self.connections = {}
def add_connection(self, connection_id):
"""Adds a new connection to this server."""
# Add the connection to the dictionary with the calculated load
connection_load = random.random()*10+1
self.connections[connection_id]= connection_load
def close_connection(self, connection_id):
"""Closes a connection on this server."""
# Remove the connection from the dictionary
del self.connections[connection_id]
def load(self):
"""Calculates the current load for all connections."""
# Add up the load for each of the connections
total = 0
for connect in self.connections.values():
total += connect
return total
def __str__(self):
"""Returns a string with the current load of the server"""
return "{:.2f}%".format(self.load())
server = Server()
server.add_connection("192.168.1.1")
print(server.load())
More information about the Tutor
mailing list