Classes and objects theory + first problem: create a Server class with hostname, IP, and status
easyClasses and objects
Problem statement
A class is a blueprint. An object is one real thing built from that blueprint.
- The class
Serversays every server has a hostname, an IP and a status. - Each object holds its own values, such as
web-01ordb-01. - The values stored inside an object are called fields.
- A special function called the constructor runs when you create an object and fills in its fields.
Instead of three loose variables per server, you keep them together in one object.
flowchart LR
A["class Server: hostname, ip, status"] --> B["object: web-01, 10.0.0.1, up"]
A --> C["object: db-01, 10.0.0.2, down"]
classDef blueprint fill:#DBEAFE,stroke:#2563EB,color:#1E3A8A
classDef obj fill:#D1FAE5,stroke:#059669,color:#065F46
class A blueprint
class B obj
class C obj
Common mistake: in Python, forgetting self. when saving a field.
TEXT
Wrong:def __init__(self, hostname): hostname = hostnameThat only sets a local variable that disappears when the constructor ends. The object never gets a hostname. Write self.hostname = hostname.
Your task: create a class Server with a hostname, an IP and a status. Build two servers: web-01 (10.0.0.1, up) and db-01 (10.0.0.2, down). Print each as <hostname> (<ip>) is <status>.
Expected output
TEXT
web-01 (10.0.0.1) is updb-01 (10.0.0.2) is downApproach
Define the class with a constructor, create the objects, then read their fields:
- Python: the constructor is
__init__. Its first parameter,self, means "this object". Fields are set withself.name = value. - Java: the constructor has the same name as the class. Fields are declared with a type.
this.hostname = hostnamesaves a value. - C++: the constructor also has the class name. Fields are marked
public:somaincan read them. Java and C++ need the type of every field written out.
In the Java file, Main comes first because java Main.java starts from the first class in the file.
class Server:
def __init__(self, hostname, ip, status):
self.hostname = hostname
self.ip = ip
self.status = status
servers = [Server("web-01", "10.0.0.1", "up"), Server("db-01", "10.0.0.2", "down")]
for server in servers:
print(f"{server.hostname} ({server.ip}) is {server.status}")