Practical Example: Server Class with check_status()

🏷️ Object-Oriented Programming (OOP) Basics / Instance Methods

📝 Context Introduction

When managing servers in a real-world environment, you often need to track each server's details and check whether it's running properly. Instead of writing separate variables and functions for every server, we can create a Server class that acts as a blueprint. Each server we create from this class will have its own attributes (like name, IP address, and status) and its own behaviors (like checking its status). This makes our code cleaner, reusable, and much easier to maintain as our server fleet grows.


⚙️ What We Are Building

We are going to build a simple Server class that: - Stores basic information about a server (name, IP address, and current status). - Has an instance method called check_status() that simulates checking whether the server is online or offline. - Allows us to create multiple server objects, each with its own independent data.


🛠️ Step-by-Step Breakdown

1️⃣ Defining the Server Class

We start by defining the class using the class keyword. Inside the class, we define an init method (the constructor) that runs automatically when we create a new server object. This method sets up the initial attributes for each server.

  • The init method takes three parameters: self, name, ip_address, and status.
  • self refers to the specific server object being created.
  • We store the values as instance attributes: self.name, self.ip_address, and self.status.

2️⃣ Creating the check_status() Method

The check_status() method is an instance method — it belongs to each server object and can access that object's attributes using self.

  • This method checks the current self.status attribute.
  • If the status is "running", it prints a message saying the server is online.
  • If the status is "stopped", it prints a message saying the server is offline.
  • If the status is anything else, it prints a message saying the status is unknown.

3️⃣ Creating Server Objects

Once the class is defined, we can create as many server objects as we need. Each object gets its own copy of the attributes and methods.

  • We call the class like a function, passing the required arguments: name, ip_address, and status.
  • The result is stored in a variable representing that specific server.

4️⃣ Calling the Method

We call the check_status() method on each server object using dot notation: server_object.check_status().

  • Each server object runs its own version of the method, using its own stored data.

📊 Comparison: Without Class vs. With Class

Aspect Without Class (Procedural) With Class (OOP)
Data Storage Separate variables for each server (e.g., server1_name, server2_ip) Attributes stored inside each object (e.g., server1.name, server2.ip)
Code Reusability Must rewrite logic for each new server Define once in the class, reuse for all servers
Maintainability Changes require updating every server's code Change the class method, all objects benefit
Scalability Becomes messy with many servers Clean and organized, easy to add more servers

🕵️ Full Example Walkthrough

Step 1: Define the Server class

We write the class with the init method to set up name, ip_address, and status. Then we define the check_status() instance method.

  • The init method stores the three values as instance attributes.
  • The check_status() method uses an if-elif-else structure to evaluate self.status and print the appropriate message.

Step 2: Create server objects

We create two servers: - web_server with name "WebServer", IP "192.168.1.10", and status "running". - db_server with name "DBServer", IP "192.168.1.20", and status "stopped".

Step 3: Call the check_status() method on each server

  • For web_server, the method checks self.status which is "running", so it prints that the server is online.
  • For db_server, the method checks self.status which is "stopped", so it prints that the server is offline.

Expected output from the example:

  • WebServer (192.168.1.10) is ONLINE and running.
  • DBServer (192.168.1.20) is OFFLINE and stopped.

💡 Key Takeaways

  • A class is a blueprint for creating objects that share common attributes and methods.
  • The init method initializes each object's unique data when it is created.
  • Instance methods like check_status() operate on the data stored inside a specific object using self.
  • Each object (server) is independent — changing one server's status does not affect others.
  • This approach makes it easy to add new servers, modify behavior in one place, and keep your code organized as your infrastructure grows.

🚀 Next Steps

Now that you understand how to create a class with instance methods, try extending this example on your own: - Add a restart() method that changes the status to "running". - Add a stop() method that changes the status to "stopped". - Create a list of server objects and loop through them to check all statuses at once.

Practice building small classes like this to get comfortable with the OOP mindset — it will make managing complex systems much easier.


A Server class with a check_status() method simulates monitoring a server's health by returning its current operational state.

🔧 Example 1: Basic Server class with status attribute

This example shows the simplest possible Server class that stores and returns a status string.

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

    def check_status(self):
        return self.status

server_a = Server("online")
result = server_a.check_status()
print(result)

📤 Output: online


🔧 Example 2: Server with default status

This example shows how to set a default status when no status is provided during creation.

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

    def check_status(self):
        return self.status

server_b = Server()
result = server_b.check_status()
print(result)

📤 Output: unknown


🔧 Example 3: Server with dynamic status update

This example shows how to change the server status after creation and then check it again.

class Server:
    def __init__(self, name, status="offline"):
        self.name = name
        self.status = status

    def check_status(self):
        return f"{self.name} is {self.status}"

server_c = Server("web-01")
print(server_c.check_status())
server_c.status = "online"
print(server_c.check_status())

📤 Output: web-01 is offline
📤 Output: web-01 is online


🔧 Example 4: Server with status validation

This example shows how to validate that only allowed status values can be assigned to a server.

class Server:
    VALID_STATUSES = ["online", "offline", "maintenance", "error"]

    def __init__(self, name, status="offline"):
        self.name = name
        if status in self.VALID_STATUSES:
            self.status = status
        else:
            self.status = "unknown"

    def check_status(self):
        return f"Server {self.name}: {self.status}"

server_d = Server("db-01", "online")
print(server_d.check_status())
server_e = Server("db-02", "crashed")
print(server_e.check_status())

📤 Output: Server db-01: online
📤 Output: Server db-02: unknown


🔧 Example 5: Server with multiple servers and status reporting

This example shows how to create multiple servers and check their status in a loop.

class Server:
    def __init__(self, name, status="offline"):
        self.name = name
        self.status = status

    def check_status(self):
        return f"{self.name} -> {self.status}"

servers = [
    Server("web-01", "online"),
    Server("web-02", "online"),
    Server("db-01", "maintenance"),
    Server("cache-01", "offline")
]

for server in servers:
    print(server.check_status())

📤 Output: web-01 -> online
📤 Output: web-02 -> online
📤 Output: db-01 -> maintenance
📤 Output: cache-01 -> offline


Comparison Table

Feature Example 1 Example 2 Example 3 Example 4 Example 5
Default status No Yes Yes Yes Yes
Status update No No Yes No No
Status validation No No No Yes No
Multiple servers No No No No Yes
Custom message format No No Yes Yes Yes

📝 Context Introduction

When managing servers in a real-world environment, you often need to track each server's details and check whether it's running properly. Instead of writing separate variables and functions for every server, we can create a Server class that acts as a blueprint. Each server we create from this class will have its own attributes (like name, IP address, and status) and its own behaviors (like checking its status). This makes our code cleaner, reusable, and much easier to maintain as our server fleet grows.


⚙️ What We Are Building

We are going to build a simple Server class that: - Stores basic information about a server (name, IP address, and current status). - Has an instance method called check_status() that simulates checking whether the server is online or offline. - Allows us to create multiple server objects, each with its own independent data.


🛠️ Step-by-Step Breakdown

1️⃣ Defining the Server Class

We start by defining the class using the class keyword. Inside the class, we define an init method (the constructor) that runs automatically when we create a new server object. This method sets up the initial attributes for each server.

  • The init method takes three parameters: self, name, ip_address, and status.
  • self refers to the specific server object being created.
  • We store the values as instance attributes: self.name, self.ip_address, and self.status.

2️⃣ Creating the check_status() Method

The check_status() method is an instance method — it belongs to each server object and can access that object's attributes using self.

  • This method checks the current self.status attribute.
  • If the status is "running", it prints a message saying the server is online.
  • If the status is "stopped", it prints a message saying the server is offline.
  • If the status is anything else, it prints a message saying the status is unknown.

3️⃣ Creating Server Objects

Once the class is defined, we can create as many server objects as we need. Each object gets its own copy of the attributes and methods.

  • We call the class like a function, passing the required arguments: name, ip_address, and status.
  • The result is stored in a variable representing that specific server.

4️⃣ Calling the Method

We call the check_status() method on each server object using dot notation: server_object.check_status().

  • Each server object runs its own version of the method, using its own stored data.

📊 Comparison: Without Class vs. With Class

Aspect Without Class (Procedural) With Class (OOP)
Data Storage Separate variables for each server (e.g., server1_name, server2_ip) Attributes stored inside each object (e.g., server1.name, server2.ip)
Code Reusability Must rewrite logic for each new server Define once in the class, reuse for all servers
Maintainability Changes require updating every server's code Change the class method, all objects benefit
Scalability Becomes messy with many servers Clean and organized, easy to add more servers

🕵️ Full Example Walkthrough

Step 1: Define the Server class

We write the class with the init method to set up name, ip_address, and status. Then we define the check_status() instance method.

  • The init method stores the three values as instance attributes.
  • The check_status() method uses an if-elif-else structure to evaluate self.status and print the appropriate message.

Step 2: Create server objects

We create two servers: - web_server with name "WebServer", IP "192.168.1.10", and status "running". - db_server with name "DBServer", IP "192.168.1.20", and status "stopped".

Step 3: Call the check_status() method on each server

  • For web_server, the method checks self.status which is "running", so it prints that the server is online.
  • For db_server, the method checks self.status which is "stopped", so it prints that the server is offline.

Expected output from the example:

  • WebServer (192.168.1.10) is ONLINE and running.
  • DBServer (192.168.1.20) is OFFLINE and stopped.

💡 Key Takeaways

  • A class is a blueprint for creating objects that share common attributes and methods.
  • The init method initializes each object's unique data when it is created.
  • Instance methods like check_status() operate on the data stored inside a specific object using self.
  • Each object (server) is independent — changing one server's status does not affect others.
  • This approach makes it easy to add new servers, modify behavior in one place, and keep your code organized as your infrastructure grows.

🚀 Next Steps

Now that you understand how to create a class with instance methods, try extending this example on your own: - Add a restart() method that changes the status to "running". - Add a stop() method that changes the status to "stopped". - Create a list of server objects and loop through them to check all statuses at once.

Practice building small classes like this to get comfortable with the OOP mindset — it will make managing complex systems much easier.

Interactive Views

You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.

A Server class with a check_status() method simulates monitoring a server's health by returning its current operational state.

🔧 Example 1: Basic Server class with status attribute

This example shows the simplest possible Server class that stores and returns a status string.

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

    def check_status(self):
        return self.status

server_a = Server("online")
result = server_a.check_status()
print(result)

📤 Output: online


🔧 Example 2: Server with default status

This example shows how to set a default status when no status is provided during creation.

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

    def check_status(self):
        return self.status

server_b = Server()
result = server_b.check_status()
print(result)

📤 Output: unknown


🔧 Example 3: Server with dynamic status update

This example shows how to change the server status after creation and then check it again.

class Server:
    def __init__(self, name, status="offline"):
        self.name = name
        self.status = status

    def check_status(self):
        return f"{self.name} is {self.status}"

server_c = Server("web-01")
print(server_c.check_status())
server_c.status = "online"
print(server_c.check_status())

📤 Output: web-01 is offline
📤 Output: web-01 is online


🔧 Example 4: Server with status validation

This example shows how to validate that only allowed status values can be assigned to a server.

class Server:
    VALID_STATUSES = ["online", "offline", "maintenance", "error"]

    def __init__(self, name, status="offline"):
        self.name = name
        if status in self.VALID_STATUSES:
            self.status = status
        else:
            self.status = "unknown"

    def check_status(self):
        return f"Server {self.name}: {self.status}"

server_d = Server("db-01", "online")
print(server_d.check_status())
server_e = Server("db-02", "crashed")
print(server_e.check_status())

📤 Output: Server db-01: online
📤 Output: Server db-02: unknown


🔧 Example 5: Server with multiple servers and status reporting

This example shows how to create multiple servers and check their status in a loop.

class Server:
    def __init__(self, name, status="offline"):
        self.name = name
        self.status = status

    def check_status(self):
        return f"{self.name} -> {self.status}"

servers = [
    Server("web-01", "online"),
    Server("web-02", "online"),
    Server("db-01", "maintenance"),
    Server("cache-01", "offline")
]

for server in servers:
    print(server.check_status())

📤 Output: web-01 -> online
📤 Output: web-02 -> online
📤 Output: db-01 -> maintenance
📤 Output: cache-01 -> offline


Comparison Table

Feature Example 1 Example 2 Example 3 Example 4 Example 5
Default status No Yes Yes Yes Yes
Status update No No Yes No No
Status validation No No No Yes No
Multiple servers No No No No Yes
Custom message format No No Yes Yes Yes