π’ Office System
in Python
Build an Office management system in Python: employees, managers, departments and payroll using inheritance, composition and polymorphism.
What this lesson is about
An office is a perfect place to learn object-oriented design, because you already understand how it works. There are employees, some of them are managers, they belong to departments, they get paid, and the company needs reports. Every one of those nouns becomes a class, and every verb becomes a method.
The project teaches the question that decides most designs: is this an is-a relationship or a has-a relationship? A manager is an employee, so inheritance fits. A department has employees, so composition fits. Mixing the two up is the most common design mistake in beginner object-oriented code.
I build the office in small steps: a base Employee, specialised roles, a Department that holds people, payroll that treats every role the same way, and finally a report. All code runs in your browser, uses only the standard library and prints the same output every time.
By the end you will have a small but complete system: people with roles, departments that hold them, an office that moves them around and reports that add up. More importantly, you will have a feel for where each piece of logic belongs, which is the real skill behind object-oriented design and the reason this project is worth building slowly and reading carefully.
What you will learn
- βModelling real objects as classes
- βUsing inheritance for is-a relationships
- βUsing composition for has-a relationships
- βOverriding methods and calling
super() - βPolymorphic payroll that works for every role
- βClass attributes, properties and validation
- βSorting and grouping objects for reports
- βWhen to prefer composition over inheritance
Why programmers should learn this
- β Employees, orders, accounts and invoices follow the same patterns, so this project transfers to almost any business program.
- β It makes the difference between inheritance and composition concrete instead of theoretical.
- β Payroll gives a natural reason for polymorphism: one loop, many kinds of employee.
- β Validation and properties show how classes protect their own data.
- β Reports practise sorting, grouping and formatting, which are everyday skills.
Start with a plain Employee class
Every design begins with the thing everyone shares. Every person in the office has a name, an id and a monthly salary. I put those in an Employee class and give it two behaviours: describing itself and computing monthly pay.
I validate in the constructor. A negative salary is a bug, and the best moment to catch a bug is when the object is created, not when payroll runs. A short ValueError with a clear message is enough.
The __repr__ method deserves a line of its own. When you print a list of objects while debugging, a good representation turns unreadable memory addresses into something you can understand at a glance.
Before moving on, run the example and change a value. Try a salary of zero, then a very large number, then a string. Seeing which of these the class accepts and which it rejects teaches you more about validation than reading about it. A class is a promise about what its objects will always look like, and the constructor is where that promise is made.
class Employee:
def __init__(self, emp_id, name, salary):
if salary < 0:
raise ValueError("salary cannot be negative")
self.emp_id = emp_id
self.name = name
self.salary = salary
def monthly_pay(self):
return round(self.salary / 12, 2)
def __repr__(self):
return f"Employee({self.emp_id!r}, {self.name!r}, {self.salary})"
ana = Employee(1, "Ana", 36000)
print(ana)
print("pay:", ana.monthly_pay())
try:
Employee(2, "Ben", -5)
except ValueError as error:
print("rejected:", error)Employee(1, 'Ana', 36000) pay: 3000.0 rejected: salary cannot be negative
Line by line
- 2-7The constructor checks the salary before storing anything, so an invalid object can never exist.
- 9-10
monthly_paydivides the yearly salary by twelve and rounds to two decimals. - 12-13
__repr__returns text that looks like the code that built the object.!radds quotes around strings. - 16-18Create an employee, print it and show her monthly pay.
- 20-23A negative salary raises
ValueError, which we catch and print.
Validate in the constructor. An object that cannot be created invalid never needs to be re-checked later.
Inheritance: managers, engineers and interns
A manager is an employee with extras: a bonus and a team. An engineer is an employee with an overtime rate. Because each of them is an employee, they inherit the shared behaviour and add or change only what is different.
super().__init__ hands the shared arguments to the parent so the code is not repeated. Overriding monthly_pay lets each role compute pay in its own way. The call site never changes: person.monthly_pay() works for everyone.
Keep inheritance shallow. Two levels, base class and role, is easy to follow. A chain of five classes means readers must open five files to answer one question.
Think about what the subclasses cost you. Every override is a place where the child's behaviour can drift from the parent's, so each one should be deliberate. A good test is the substitution rule: anywhere the code expects an employee, a manager must work just as well. If a subclass breaks that expectation, for example by raising an error where the parent returned a number, the inheritance is probably wrong.
class Employee:
def __init__(self, emp_id, name, salary):
if salary < 0:
raise ValueError("salary cannot be negative")
self.emp_id, self.name, self.salary = emp_id, name, salary
def monthly_pay(self):
return round(self.salary / 12, 2)
def title(self):
return "Employee"
def __repr__(self):
return f"{self.title()}({self.name})"
class Manager(Employee):
def __init__(self, emp_id, name, salary, bonus):
super().__init__(emp_id, name, salary)
self.bonus = bonus
def monthly_pay(self):
return round(super().monthly_pay() + self.bonus / 12, 2)
def title(self):
return "Manager"
class Engineer(Employee):
def __init__(self, emp_id, name, salary, overtime_hours=0, rate=20):
super().__init__(emp_id, name, salary)
self.overtime_hours = overtime_hours
self.rate = rate
def monthly_pay(self):
return round(super().monthly_pay() + self.overtime_hours * self.rate, 2)
def title(self):
return "Engineer"
people = [Employee(1, "Ana", 36000), Manager(2, "Ben", 60000, bonus=6000), Engineer(3, "Cora", 48000, overtime_hours=5)]
for person in people:
print(f"{person!r:20} {person.monthly_pay():>9.2f}")
print(isinstance(people[1], Employee), isinstance(people[0], Manager))Employee(Ana) 3000.00 Manager(Ben) 5500.00 Engineer(Cora) 4100.00 True False
Line by line
- 1-15The base class now has a
titlemethod so every role can describe itself. - 18-27
Managercallssuper().__init__for the shared fields, stores a bonus and overridesmonthly_payto add a twelfth of the bonus. - 30-40
Engineeradds overtime hours and a rate, and overrides pay in the same way. - 43-45One loop prints pay for three different classes. The formatting
:20and:>9.2faligns the columns. - 46A manager is an employee, but an employee is not a manager.
isinstanceconfirms it.
super() gives you the parent's version of a method. Extend the parent's behaviour instead of copying it.
Composition: a Department has employees
A department is not a kind of employee. It has employees. That is composition: one object holds others. The department stores a list of people and offers methods to add, find and total them.
I prefer composition whenever the relationship is has-a, because it keeps classes independent. The department does not need to know how a manager computes pay. It only asks each person for monthly_pay(). That is polymorphism working across composition.
The department also guards its own rules. It refuses to add the same id twice. Rules about a collection belong in the class that owns the collection.
A department that exposes its dictionary directly invites other code to change it behind its back. By offering methods such as add and find, the class keeps the right to enforce its rules. This idea is called encapsulation, and it is what lets you change the inside of a class later, for example replacing a dictionary with a database, without rewriting every caller.
class Employee:
def __init__(self, emp_id, name, salary):
self.emp_id, self.name, self.salary = emp_id, name, salary
def monthly_pay(self):
return round(self.salary / 12, 2)
class Manager(Employee):
def __init__(self, emp_id, name, salary, bonus):
super().__init__(emp_id, name, salary)
self.bonus = bonus
def monthly_pay(self):
return round(super().monthly_pay() + self.bonus / 12, 2)
class Department:
def __init__(self, name):
self.name = name
self._people = {}
def add(self, person):
if person.emp_id in self._people:
raise ValueError(f"id {person.emp_id} already in {self.name}")
self._people[person.emp_id] = person
def find(self, emp_id):
return self._people.get(emp_id)
def payroll(self):
return round(sum(p.monthly_pay() for p in self._people.values()), 2)
def __len__(self):
return len(self._people)
sales = Department("Sales")
sales.add(Employee(1, "Ana", 36000))
sales.add(Manager(2, "Ben", 60000, 6000))
print(len(sales), "people, payroll", sales.payroll())
print(sales.find(2).name, sales.find(99))
try:
sales.add(Employee(1, "Dup", 1000))
except ValueError as error:
print("rejected:", error)2 people, payroll 8500.0 Ben None rejected: id 1 already in Sales
Line by line
- 19-35
Departmentstores people in a dictionary keyed by id, which makes lookups fast and duplicates easy to spot. - 21-23The leading underscore in
_peoplesignals that outside code should use the methods instead. - 28-29
findusesdict.get, which returnsNoneinstead of raising when the id is missing. - 31-32
payrolltotals pay by asking each person; it does not care what class they are. - 38-42Build a department, add two people and print the headcount and total.
- 44-47Adding a duplicate id is rejected by the department itself.
Properties and class attributes
Two small features make classes safer. A property lets you run code when an attribute is read or written, so a salary can be validated every time it changes, not only in the constructor. A class attribute is shared by every instance, which suits company-wide constants such as the number of months in a pay year.
Use a property when you want the simple look of person.salary but need control behind it. Callers do not change how they write the code, and you can add rules later without breaking them.
In the example, the raise method uses the property to apply a percentage and still gets validation for free.
Properties are also how Python avoids the getter and setter boilerplate seen in other languages. You start with a plain attribute, and only when a rule appears do you convert it to a property. Callers keep writing the same code, which is why experienced Python programmers rarely write get and set methods by hand.
class Employee:
MONTHS = 12
raises_given = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
@property
def salary(self):
return self._salary
@salary.setter
def salary(self, value):
if value < 0:
raise ValueError("salary cannot be negative")
self._salary = value
def monthly_pay(self):
return round(self.salary / self.MONTHS, 2)
def give_raise(self, percent):
self.salary = round(self.salary * (1 + percent / 100))
Employee.raises_given += 1
ana = Employee("Ana", 36000)
ana.give_raise(10)
print(ana.salary, ana.monthly_pay())
try:
ana.salary = -1
except ValueError as error:
print("rejected:", error)
Employee("Ben", 1000).give_raise(5)
print("raises given:", Employee.raises_given)39600 3300.0 rejected: salary cannot be negative raises given: 2
Line by line
- 2-3
MONTHSandraises_givenbelong to the class and are shared by all instances. - 9-17The
salaryproperty reads_salary, and the setter validates before storing. The constructor assignmentself.salary = salaryalso goes through the setter. - 22-24
give_raisechanges the salary through the property and increments the shared counter on the class. - 27-33Raise Ana's pay, try an invalid value, then show that the class counter saw two raises.
Polymorphic payroll and reports
Now the payoff. A payroll function loops over a list of people and asks each for monthly_pay(). It does not check types. Add a new role next year, such as a contractor, and payroll keeps working without a single edit.
Reports need sorting and grouping. sorted with a key function orders people by pay, and a dictionary groups them by title. These are standard tools you will use in every data program.
The example prints a small table. Pay attention to the format specifiers: they are the difference between output that looks like a report and output that looks like debugging.
Reports are where object design meets real users. A manager reading the payroll does not care about classes; they care that the numbers add up and the columns line up. Spend time on the output: align the columns, round money consistently and always show a total so a reader can spot a mistake quickly.
Contractors show how far polymorphism can stretch. They have no salary at all, yet the payroll code does not notice, because it only asks for monthly pay. Whenever you catch yourself adding a special case in the caller, ask whether the special case belongs inside a method of the object instead.
from collections import defaultdict
class Employee:
role = "Employee"
def __init__(self, name, salary):
self.name, self.salary = name, salary
def monthly_pay(self):
return round(self.salary / 12, 2)
class Manager(Employee):
role = "Manager"
def __init__(self, name, salary, bonus):
super().__init__(name, salary)
self.bonus = bonus
def monthly_pay(self):
return round(super().monthly_pay() + self.bonus / 12, 2)
class Contractor(Employee):
role = "Contractor"
def __init__(self, name, hours, rate):
super().__init__(name, 0)
self.hours, self.rate = hours, rate
def monthly_pay(self):
return round(self.hours * self.rate, 2)
staff = [Employee("Ana", 36000), Manager("Ben", 60000, 6000),
Contractor("Dev", 80, 25), Employee("Eli", 30000)]
print(f"{'Name':8}{'Role':12}{'Monthly':>10}")
for person in sorted(staff, key=lambda p: p.monthly_pay(), reverse=True):
print(f"{person.name:8}{person.role:12}{person.monthly_pay():>10.2f}")
groups = defaultdict(list)
for person in staff:
groups[person.role].append(person.name)
print(dict(groups))
print("total:", round(sum(p.monthly_pay() for p in staff), 2))Name Role Monthly
Ben Manager 5500.00
Ana Employee 3000.00
Eli Employee 2500.00
Dev Contractor 2000.00
{'Employee': ['Ana', 'Eli'], 'Manager': ['Ben'], 'Contractor': ['Dev']}
total: 13000.0Line by line
- 1
defaultdictcreates an empty list automatically the first time a key is used. - 4-5A class attribute
rolenames each class for the report. - 27-35
Contractoris paid by the hour, so it overridesmonthly_paycompletely and never uses a salary. - 38-39Four people of three kinds in one list.
- 41-44Sort by pay from highest to lowest and print a table with fixed column widths.
- 46-49Group names by role and total the payroll. No
ifmentions a class.
If you find yourself writing if type(x) is Manager in a loop, move that difference into a method on the class instead.
Composition over inheritance: permissions
Inheritance is tempting, but it can trap you. Suppose some employees can approve expenses and some can hire. If you build a class for every combination, the tree explodes. A better answer is composition: give each person a set of abilities.
I model abilities as a small set of strings and ask can('approve'). Adding a new ability changes data, not classes. This is the heart of the advice you will hear everywhere: favour composition over inheritance when behaviour varies in several independent ways.
Inheritance still has its place for stable is-a relationships, such as a manager being an employee. The skill is to know which one you are looking at.
The same idea appears in games and apps. A character has abilities, a user has permissions, a file has attributes. Whenever behaviour can be switched on and off independently, store it as data and let one class read that data. You get flexibility without creating a new class for every combination.
Notice how much the permissions example changed the way you think. The question is no longer which class a person belongs to, but which abilities they currently hold. That shift from type to capability is common in security systems, game design and web frameworks, and it is one of the most useful ideas you can take from this lesson into larger projects.
class Person:
def __init__(self, name, abilities=()):
self.name = name
self.abilities = set(abilities)
def can(self, ability):
return ability in self.abilities
def grant(self, ability):
self.abilities.add(ability)
def approve_expense(person, amount):
if not person.can("approve"):
return f"{person.name}: not allowed to approve"
return f"{person.name}: approved {amount}"
ana = Person("Ana")
ben = Person("Ben", {"approve", "hire"})
print(approve_expense(ana, 500))
print(approve_expense(ben, 500))
ana.grant("approve")
print(approve_expense(ana, 500))
print(sorted(ben.abilities))Ana: not allowed to approve Ben: approved 500 Ana: approved 500 ['approve', 'hire']
Line by line
- 1-9A person holds a set of abilities.
canchecks membership andgrantadds one. - 12-15The approval rule depends on an ability, not on a class.
- 18-24Ana starts without the ability and gains it later at runtime, something a class hierarchy cannot do.
Putting the office together
Finally I combine everything into one Office that owns departments. It can hire, transfer people between departments and print a summary. The code is longer than earlier examples, but each part is something you already understand.
Notice the layers. Employee and its subclasses describe people. Department holds them. Office holds departments. Each class has a single job, and each depends only on the interface of the one below it.
Try extending it yourself afterwards: add a Contractor role, a method to find the highest-paid person, or a report saved to CSV. If a change needs edits in many places, that is a hint to rethink the design.
As a final exercise, write down the classes of a school, a shop or a hospital before you write any code. List the nouns, decide which are is-a and which are has-a, and sketch the methods each class needs. A ten minute sketch like this saves hours of rewriting, and it is the habit that separates tidy projects from tangled ones.
When you run the final example, trace one transfer by hand. Ana leaves the Sales dictionary, enters the Engineering dictionary, and both payroll totals change without any extra code. That is the reward for giving each class one job: the behaviour you wanted emerges from small parts that each do something simple and do it correctly every time.
class Employee:
def __init__(self, emp_id, name, salary):
self.emp_id, self.name, self.salary = emp_id, name, salary
def monthly_pay(self):
return round(self.salary / 12, 2)
class Manager(Employee):
def __init__(self, emp_id, name, salary, bonus):
super().__init__(emp_id, name, salary)
self.bonus = bonus
def monthly_pay(self):
return round(super().monthly_pay() + self.bonus / 12, 2)
class Department:
def __init__(self, name):
self.name, self.people = name, {}
def add(self, person):
self.people[person.emp_id] = person
def remove(self, emp_id):
return self.people.pop(emp_id)
def payroll(self):
return round(sum(p.monthly_pay() for p in self.people.values()), 2)
class Office:
def __init__(self):
self.departments = {}
def hire(self, dept, person):
self.departments.setdefault(dept, Department(dept)).add(person)
def transfer(self, emp_id, source, target):
person = self.departments[source].remove(emp_id)
self.departments[target].add(person)
def summary(self):
for name, dept in sorted(self.departments.items()):
names = ", ".join(p.name for p in dept.people.values()) or "-"
print(f"{name:12} {len(dept.people)} people {dept.payroll():>9.2f} [{names}]")
office = Office()
office.hire("Sales", Employee(1, "Ana", 36000))
office.hire("Sales", Manager(2, "Ben", 60000, 6000))
office.hire("Engineering", Employee(3, "Cora", 48000))
office.summary()
print("--- Ana moves to Engineering ---")
office.transfer(1, "Sales", "Engineering")
office.summary()Engineering 1 people 4000.00 [Cora] Sales 2 people 8500.00 [Ana, Ben] --- Ana moves to Engineering --- Engineering 2 people 7000.00 [Cora, Ana] Sales 1 people 5500.00 [Ben]
Line by line
- 19-30
Departmentis a simple container with add, remove and payroll. - 33-48
Officeowns departments.hirecreates a department on first use withsetdefault.transferremoves a person from one department and adds them to another. - 40-43
summaryprints one line per department with the names and total pay. - 51-58Hire three people, print the summary, move Ana and print again to see the change.
Common mistakes
β Using inheritance for a has-a relationship
A department is not a kind of employee. If the sentence 'X is a Y' sounds wrong, use composition instead.
β Copying parent code into the child
Call super() to extend the parent's behaviour. Copied code gets out of date.
β Checking types in loops
if type(p) is Manager brings back the if chain. Put the difference in an overridden method.
β Deep inheritance chains
More than two levels makes code hard to follow. Prefer a shallow hierarchy plus composition.
β Letting objects hold invalid data
Validate in the constructor and in property setters so a bad value is rejected at the moment it appears.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. Which relationship suggests inheritance?
Q2. What does super().monthly_pay() do in a subclass?
super() gives access to the parent's method so you can extend it.Q3. Why use a property for salary?
Q4. What makes payroll polymorphic here?
Q5. Why model abilities as a set of strings?
Q6. Where should the duplicate-id rule live?
Frequently asked questions
When should I use inheritance?
+When the relationship is truly is-a and the child can be used wherever the parent is expected. If you only want to reuse code, composition is usually better.
What is the difference between a class and instance attribute?
+A class attribute is shared by every instance, like MONTHS. An instance attribute belongs to one object, like salary.
Why the underscore in _people?
+It is a convention that says the attribute is internal. Python does not enforce it, but other programmers will respect it.
Can a class inherit from two parents?
+Yes, Python supports multiple inheritance, but it is easy to get wrong. Prefer composition unless you have a clear reason.
How would I save the office to a file?
+Add a to_dict method to each class and write the result with the json module. Loading reverses the steps.
Key takeaways
- βModel real nouns as classes and real verbs as methods.
- βInherit for is-a relationships and compose for has-a relationships.
- βOverride methods and call
super()instead of copying code. - βPolymorphism lets one loop handle every role.
- βProperties validate data each time it changes.
- βPrefer composition when behaviour varies in several independent ways.