Chapter 08
Object-oriented Python
Classes and instances
A class groups data and behavior. self refers to the instance. __init__ initializes new objects.
class Server:
def __init__(self, name, port=80):
self.name = name
self.port = port
def address(self):
return f"{self.name}:{self.port}"
s = Server("localhost", 8080)
print(s.address())Hands-on lab: Create two Server instances with different ports.
Methods and encapsulation
Methods are functions defined on classes. Favor simple composition and clear interfaces over unnecessary inheritance.
class Counter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1Hands-on lab: Add a reset method and test it.
Final object exercise
Model a small inventory of services with name, port and running state. Add a method to produce a human-readable summary.
Hands-on lab: Create a list of three objects and print a report.