Home β€Ί Curriculum β€Ί Office System
Updated for Python 3.12+ Β· November 2026

🏒 Office System
in Python

Build an Office management system in Python: employees, managers, departments and payroll using inheritance, composition and polymorphism.

Intermediate 7 lessonsβ‰ˆ 40 min read by Glenn Pansensoy

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.

python
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)
Expected output
Employee(1, 'Ana', 36000)
pay: 3000.0
rejected: salary cannot be negative

Line by line

  1. 2-7The constructor checks the salary before storing anything, so an invalid object can never exist.
  2. 9-10monthly_pay divides the yearly salary by twelve and rounds to two decimals.
  3. 12-13__repr__ returns text that looks like the code that built the object. !r adds quotes around strings.
  4. 16-18Create an employee, print it and show her monthly pay.
  5. 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.

python
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))
Expected output
Employee(Ana)          3000.00
Manager(Ben)           5500.00
Engineer(Cora)         4100.00
True False

Line by line

  1. 1-15The base class now has a title method so every role can describe itself.
  2. 18-27Manager calls super().__init__ for the shared fields, stores a bonus and overrides monthly_pay to add a twelfth of the bonus.
  3. 30-40Engineer adds overtime hours and a rate, and overrides pay in the same way.
  4. 43-45One loop prints pay for three different classes. The formatting :20 and :>9.2f aligns the columns.
  5. 46A manager is an employee, but an employee is not a manager. isinstance confirms 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.

python
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)
Expected output
2 people, payroll 8500.0
Ben None
rejected: id 1 already in Sales

Line by line

  1. 19-35Department stores people in a dictionary keyed by id, which makes lookups fast and duplicates easy to spot.
  2. 21-23The leading underscore in _people signals that outside code should use the methods instead.
  3. 28-29find uses dict.get, which returns None instead of raising when the id is missing.
  4. 31-32payroll totals pay by asking each person; it does not care what class they are.
  5. 38-42Build a department, add two people and print the headcount and total.
  6. 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.

python
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)
Expected output
39600 3300.0
rejected: salary cannot be negative
raises given: 2

Line by line

  1. 2-3MONTHS and raises_given belong to the class and are shared by all instances.
  2. 9-17The salary property reads _salary, and the setter validates before storing. The constructor assignment self.salary = salary also goes through the setter.
  3. 22-24give_raise changes the salary through the property and increments the shared counter on the class.
  4. 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.

python
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))
Expected output
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.0

Line by line

  1. 1defaultdict creates an empty list automatically the first time a key is used.
  2. 4-5A class attribute role names each class for the report.
  3. 27-35Contractor is paid by the hour, so it overrides monthly_pay completely and never uses a salary.
  4. 38-39Four people of three kinds in one list.
  5. 41-44Sort by pay from highest to lowest and print a table with fixed column widths.
  6. 46-49Group names by role and total the payroll. No if mentions 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.

python
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))
Expected output
Ana: not allowed to approve
Ben: approved 500
Ana: approved 500
['approve', 'hire']

Line by line

  1. 1-9A person holds a set of abilities. can checks membership and grant adds one.
  2. 12-15The approval rule depends on an ability, not on a class.
  3. 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.

python
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()
Expected output
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

  1. 19-30Department is a simple container with add, remove and payroll.
  2. 33-48Office owns departments. hire creates a department on first use with setdefault. transfer removes a person from one department and adds them to another.
  3. 40-43summary prints one line per department with the names and total pay.
  4. 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?

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 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.

A class attribute is shared by every instance, like MONTHS. An instance attribute belongs to one object, like salary.

It is a convention that says the attribute is internal. Python does not enforce it, but other programmers will respect it.

Yes, Python supports multiple inheritance, but it is easy to get wrong. Prefer composition unless you have a clear reason.

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.