Programming from zero

Add a restart method to the Server class

easyClasses and objects

Problem statement

A method is a function that lives inside a class. It works on the object it is called on, so it can read and change that object's fields.

  • Fields describe what an object is (hostname, status).
  • Methods describe what an object can do (restart, describe).
  • You call a method with a dot: server.restart().

Common mistake: changing a plain variable instead of the field.

TEXT
Wrong:
def restart(self):
status = "up"

That creates a local variable and the object's status stays down. Write self.status = "up" so the change sticks to the object.

Your task: start from the Server class (a hostname and a status). Add a method restart() that prints Restarting <hostname>... and sets the status to up. Create web-01 with status down, print <hostname> is <status>, call restart(), then print the same line again.

Expected output

TEXT
web-01 is down
Restarting web-01...
web-01 is up

Approach

Add the method inside the class, and let it change the field:

  • Python: def restart(self): and self.status = "up".
  • Java: void restart() inside the class. Fields are reachable directly, so status = "up" changes the field, and this.status also works.
  • C++: void restart() inside the class with the same idea. The method changes the object's own status.

The methods look almost identical in all three. Only the syntax around them differs.

class Server:
    def __init__(self, hostname, status):
        self.hostname = hostname
        self.status = status

    def restart(self):
        print(f"Restarting {self.hostname}...")
        self.status = "up"


server = Server("web-01", "down")
print(f"{server.hostname} is {server.status}")
server.restart()
print(f"{server.hostname} is {server.status}")