PYTHON · PYTHON FOR EVERYONE · CHAPTER 7

Object orientation

Model routers, switches and interfaces as objects that keep their state and know what to do with it.

12 min readCourse: Python for EveryoneLevel: beginner

From point A to point B

Point A: you have functions on one side and data on the other, and in a network inventory you have to pass the same dictionary to 10 different functions. Point B: by the end of this chapter, you'll model routers, switches and interfaces as objects that keep their state and know what to do with it, and you'll reuse code through inheritance.

This chapter is long and takes practice. Run every example and tweak it until the result stops surprising you.

What object-oriented programming is

Python is multi-paradigm: it supports structured programming, like what you've done so far, functional programming and object-oriented programming (OOP).

In OOP you represent the elements of your problem as objects. An object groups related state and behavior. The state lives in variables called attributes; the behavior, in functions called methods.

Think of a router. Its attributes could be the hostname, the management IP and the routing table. Its methods could be learning a route or rebooting. A class is the template that defines which attributes and methods every object of that type will have. Your edge router and the lab router share a class, but they're different objects.

Classes, objects, __init__ and self

You define a class with class, the name (in CamelCase by convention), a colon and the indented body. If the first line of the body is a string, it's the class docstring.

class Router:
    """Minimal model of a router with a route counter."""

    def __init__(self, hostname, max_routes):
        self.hostname = hostname
        self.max_routes = max_routes
        self.routes = 0
        print(f"{hostname} created with room for {max_routes} routes")

    def learn_route(self):
        if self.routes < self.max_routes:
            self.routes += 1
            print(f"{self.hostname}: {self.routes} routes in the table")
        else:
            print(f"{self.hostname}: table full, route dropped")

    def status(self):
        return "full" if self.routes == self.max_routes else "has room"


r1 = Router("edge-01", 2)
r1.learn_route()
r1.learn_route()
r1.learn_route()
print(r1.status())
print(r1.routes)

r2 = Router("edge-02", 5)
print(r2.routes, r2.status())
print(type(r1), isinstance(r1, Router))
edge-01 created with room for 2 routes
edge-01: 1 routes in the table
edge-01: 2 routes in the table
edge-01: table full, route dropped
full
2
edge-02 created with room for 5 routes
0 has room
<class '__main__.Router'> True

Creating an object from a class is called instantiating. You write the class name with parentheses, as if you were calling a function: Router("edge-01", 2). Right after creating the object, Python runs its __init__ method, which initializes it.

The names with a double underscore at the start and end aren't a whim. They mark special methods that Python calls on its own at specific moments. You'll see several at the end of the chapter.

The first parameter of every method is self: the object the method works on. The idea comes from the Modula-3 language. Thanks to self, you can tell an attribute of the object, self.hostname, from a local variable, hostname. The hostname parameter disappears when __init__ ends; the self.hostname attribute lives as long as the object.

Why does the call take 2 arguments if __init__ declares 3? Because Python passes self automatically. When you write r1.learn_route(), Python translates it to Router.learn_route(r1). Notice too that r1 and r2 have independent states.

Remember that in Python everything is an object. The strings you use every day have methods, and even functions have a type:

line = "interface gi0/1 down"
print(line.upper())
print(line.count("0"))
print(type(line), type(42), type(len))
INTERFACE GI0/1 DOWN
1
<class 'str'> <class 'int'> <class 'builtin_function_or_method'>

Inheritance and super()

Three concepts hold up OOP: inheritance, polymorphism and encapsulation. Let's start with inheritance.

When a class (the subclass) inherits from another (the superclass), it receives all of its attributes and methods. You also say the subclass “extends” the superclass. Switches, firewalls and routers have a lot in common: they all have a hostname and an IP, and they all answer a ping. That shared code goes in a Device class.

class Device:
    def __init__(self, hostname, ip):
        self.hostname = hostname
        self.ip = ip

    def ping(self):
        print(f"Reply from {self.hostname} ({self.ip})")

    def reboot(self):
        print(f"{self.hostname} is rebooting")


class Switch(Device):
    pass


class Firewall(Device):
    def __init__(self, hostname, ip, zones):
        super().__init__(hostname, ip)
        self.zones = zones

    def reboot(self):
        print(f"Saving sessions for {len(self.zones)} zones")
        super().reboot()


sw = Switch("sw-acc-01", "10.0.10.2")
sw.ping()
fw = Firewall("fw-01", "10.0.0.254", ["inside", "outside", "dmz"])
fw.ping()
fw.reboot()
print(isinstance(fw, Device), issubclass(Switch, Device))
Reply from sw-acc-01 (10.0.10.2)
Reply from fw-01 (10.0.0.254)
Saving sessions for 3 zones
fw-01 is rebooting
True True

The superclass goes in parentheses after the class name. Switch adds nothing (pass is an empty block) and still knows how to ping(). Firewall needs one extra piece of data, the zones, so it writes its own __init__. That's called overriding a method.

When you override, you often want to add steps, not replace everything. To run the superclass version, use super(), as Firewall.reboot() does.

Python 3.14 update. The book calls the parent method with Instrumento.__init__(self, precio), passing self by hand. That form still works, but in Python 3 the usual way is super().__init__(precio), with no arguments to super() and no self. Besides being shorter, it respects the resolution order when there's multiple inheritance.

Multiple inheritance and the MRO

Unlike Java or C#, Python lets a class inherit from several classes at once. Just list them separated by commas. A next-generation firewall (NGFW) routes and filters:

class Router:
    def describe(self):
        return "routes packets"


class Firewall:
    def describe(self):
        return "filters traffic"


class NGFW(Router, Firewall):
    pass


box = NGFW()
print(box.describe())
print([cls.__name__ for cls in NGFW.__mro__])
routes packets
['NGFW', 'Router', 'Firewall', 'object']

Both superclasses define describe(). Which one wins? The leftmost one in the definition: Router. Python decides with the MRO (method resolution order), the ordered list of classes where it looks up each method. You can see it in the __mro__ attribute.

The MRO really matters when 2 superclasses share an ancestor, the so-called “diamond.” If every class calls super(), Python walks the MRO and runs each method only once:

class Device:
    def boot(self):
        print("Device: loads the system")


class Router(Device):
    def boot(self):
        print("Router: brings up OSPF")
        super().boot()


class Firewall(Device):
    def boot(self):
        print("Firewall: loads policies")
        super().boot()


class NGFW(Router, Firewall):
    def boot(self):
        print("NGFW: start")
        super().boot()


NGFW().boot()
print([c.__name__ for c in NGFW.__mro__])
NGFW: start
Router: brings up OSPF
Firewall: loads policies
Device: loads the system
['NGFW', 'Router', 'Firewall', 'Device', 'object']

Notice that the super() in Router doesn't jump to Device, but to Firewall: the next one in the MRO. That's why you should always use super() in hierarchies with multiple inheritance.

Polymorphism and duck typing

Polymorphism comes from the Greek for “many forms”: objects of different classes respond to the same message. In statically typed languages, like Java or C++, you get it mostly through inheritance: wherever a Device is expected, a Firewall works.

Python is dynamically typed and requires no family ties. It only asks that the object have the method you're going to call. This is called duck typing: “if it walks like a duck and quacks like a duck, treat it as a duck.”

class Cisco:
    def backup(self):
        return "show running-config"


class Juniper:
    def backup(self):
        return "show configuration | display set"


class Linux:
    def backup(self):
        return "cat /etc/network/interfaces"


for box in (Cisco(), Juniper(), Linux()):
    print(type(box).__name__, "→", box.backup())
Cisco → show running-config
Juniper → show configuration | display set
Linux → cat /etc/network/interfaces

The 3 classes share no ancestor (except object), but the loop treats them the same. This pattern is the foundation of many multivendor network automation tools.

Polymorphism sometimes also refers to method overloading: several methods with the same name told apart by the number or type of their parameters. Python doesn't have it. If you define 2 methods with the same name, the second replaces the first:

class Monitor:
    def check(self, ip):
        return f"ping {ip}"

    def check(self, ip, port):
        return f"tcp {ip}:{port}"


m = Monitor()
print(m.check("10.0.0.1", 22))
try:
    m.check("10.0.0.1")
except TypeError as error:
    print("TypeError:", error)


class BetterMonitor:
    def check(self, ip, port=None):
        if port is None:
            return f"ping {ip}"
        return f"tcp {ip}:{port}"


m2 = BetterMonitor()
print(m2.check("10.0.0.1"))
print(m2.check("10.0.0.1", 22))
tcp 10.0.0.1:22
TypeError: Monitor.check() missing 1 required positional argument: 'port'
ping 10.0.0.1
tcp 10.0.0.1:22

To mimic overloading, use default values, *args and **kwargs, as you saw in the chapter on functions, or decorators, which you'll see later on.

Encapsulation and name mangling

Encapsulation decides which parts of an object can be used from outside the class. Java does it with access modifiers like public and private. Python has no modifiers: it uses naming conventions.

  • name: public. Anyone can use it.
  • _name: one underscore means “internal use.” Python doesn't prevent access; it's an agreement between people.
  • __name: 2 leading underscores (and none trailing) trigger name mangling.
  • __name__: with underscores on both sides, it's a special method reserved for Python.
class Credentials:
    def __init__(self, user, password):
        self.user = user
        self._attempts = 0
        self.__password = password

    def validate(self, attempt):
        self._attempts += 1
        return attempt == self.__password


c = Credentials("noc", "s3cret")
print(c.validate("1234"), c.validate("s3cret"))
print(c._attempts)
try:
    print(c.__password)
except AttributeError as error:
    print("AttributeError:", error)
print(c._Credentials__password)
print([n for n in vars(c)])
False True
2
AttributeError: 'Credentials' object has no attribute '__password'
s3cret
['user', '_attempts', '_Credentials__password']

From outside, c.__password seems not to exist. In fact, Python renamed the attribute to _Credentials__password, prefixing the class name. That's why the attribute isn't truly private: with that name you can read it all the same.

The real purpose of name mangling is to avoid name clashes between a class and its subclasses, not to protect secrets. In network code, never rely on it to hide passwords: use a secrets manager or environment variables.

Getters, setters and @property

Sometimes you want to allow access to an attribute, but in a controlled way. For example, so that nobody assigns an impossible MTU. A classic solution is getter and setter methods:

class Interface:
    def __init__(self, name):
        self.name = name
        self._mtu = 1500

    def get_mtu(self):
        return self._mtu

    def set_mtu(self, value):
        if 576 <= value <= 9216:
            self._mtu = value
        else:
            print(f"MTU {value} out of range")


gi = Interface("Gi0/1")
gi.set_mtu(20000)
gi.set_mtu(9000)
print(gi.get_mtu())
MTU 20000 out of range
9000

It works, but it forces you to write gi.set_mtu(9000) instead of the natural gi.mtu = 9000. Properties solve that: they look like attributes, but under the hood they call your methods. The modern form uses the @property decorator:

class Interface:
    def __init__(self, name, mtu=1500):
        self.name = name
        self.mtu = mtu

    @property
    def mtu(self):
        return self._mtu

    @mtu.setter
    def mtu(self, value):
        if not 576 <= value <= 9216:
            raise ValueError(f"MTU {value} out of range (576-9216)")
        self._mtu = value


gi = Interface("Gi0/1")
print(gi.mtu)
gi.mtu = 9000
print(gi.mtu)
try:
    gi.mtu = 20000
except ValueError as error:
    print("ValueError:", error)
print(gi.mtu)
1500
9000
ValueError: MTU 20000 out of range (576-9216)
9000

The validation also applies inside __init__, because self.mtu = mtu goes through the setter. Instead of printing a warning, the setter raises an exception: that way the caller can't ignore the error.

The book uses the property(get, set) function. It's still valid: mtu = property(get_mtu, set_mtu) inside the class has the same effect. The decorator is just a more compact way to write it.

“New-style” classes: today they all are

The book devotes a section to “new-style” classes, which in Python 2.2 to 2.7 had to inherit from object. “Classic” classes didn't define a type of their own: all their instances were of the generic instance type. Properties, __new__ and super() only worked properly with new-style classes.

class Vlan:
    pass


class ExplicitVlan(object):
    pass


print(Vlan.__bases__, ExplicitVlan.__bases__)
print(type(Vlan()), isinstance(Vlan(), object))
print(type(Vlan))
(<class 'object'>,) (<class 'object'>,)
<class '__main__.Vlan'> True
<class 'type'>

The 2 definitions are equivalent: both inherit from object. Every class is a type of its own, and classes themselves are objects of type type.

Python 3.14 update. Python 3 removed classic classes: every class is new-style and inherits from object even if you don't write it. Writing class Vlan(object): no longer adds anything; you'll see that form in older code. Everything the book reserves for new-style classes (properties, __new__, super(), descriptors) works in any class.

Special methods

You already know __init__. Python recognizes many more double-underscore methods, sometimes called “dunder” methods. Python calls them itself when you use operators or built-in functions on your objects.

MethodWhen Python calls it
__new__(cls, ...)Before __init__, to build and return the object. It receives the class, not the instance.
__init__(self, ...)Right after the object is created, to initialize it.
__del__(self)When the object is about to be destroyed. It's the “destructor.”
__str__(self)With print(obj), str(obj) and in f-strings: text for people.
__repr__(self)With repr(obj), in the interpreter and inside lists: text for programmers.
__len__(self)With len(obj). It must return an integer greater than or equal to 0.
__contains__(self, x)With x in obj.
__getitem__(self, i)With obj[i], including slicing like obj[0:2].
__eq__, __lt__…With ==, < and the other comparisons (see the next section).

With just a few of them, your own class behaves like a native collection:

class RoutingTable:
    def __init__(self, router):
        self.router = router
        self.routes = []

    def add(self, prefix):
        self.routes.append(prefix)

    def __str__(self):
        return f"Table for {self.router}: {len(self.routes)} routes"

    def __repr__(self):
        return f"RoutingTable({self.router!r})"

    def __len__(self):
        return len(self.routes)

    def __contains__(self, prefix):
        return prefix in self.routes

    def __getitem__(self, position):
        return self.routes[position]


t = RoutingTable("core-01")
t.add("10.0.0.0/8")
t.add("172.16.0.0/12")
t.add("0.0.0.0/0")
print(t)
print(repr(t))
print([t])
print(len(t))
print("0.0.0.0/0" in t)
print(t[0], t[-1])
print(t[0:2])
for route in t:
    print(" ", route)
Table for core-01: 3 routes
RoutingTable('core-01')
[RoutingTable('core-01')]
3
True
10.0.0.0/8 0.0.0.0/0
['10.0.0.0/8', '172.16.0.0/12']
  10.0.0.0/8
  172.16.0.0/12
  0.0.0.0/0

Look at the last loop: you didn't define __iter__, but for works. If a class has __getitem__ with indexes starting at 0, Python walks through it by asking for positions until an IndexError comes up.

Now look at the order of __new__, __init__ and __del__:

class Session:
    def __new__(cls, *args):
        print(f"__new__: building a {cls.__name__} object")
        return super().__new__(cls)

    def __init__(self, host):
        print(f"__init__: opening session with {host}")
        self.host = host

    def __del__(self):
        print(f"__del__: closing session with {self.host}")


s = Session("10.0.0.1")
del s
print("End of program")
__new__: building a Session object
__init__: opening session with 10.0.0.1
__del__: closing session with 10.0.0.1
End of program

__new__ is the real constructor, equivalent to the one in C++ or Java; you'll almost never need it. Be careful with __del__: del s doesn't call it directly, it only deletes a name. In CPython it ran right away because no other references to the object remained, but the language doesn't guarantee when it happens. To close sessions or files reliably, use with, which you'll see later on.

Rich comparisons

If you don't define anything, == compares identity: 2 objects are equal only if they're the same object. And < raises an error, because Python doesn't know how to order your objects:

class Vlan:
    def __init__(self, number):
        self.number = number


a, b = Vlan(10), Vlan(10)
print(a == b, a == a)
try:
    a < b
except TypeError as error:
    print("TypeError:", error)
False True
TypeError: '<' not supported between instances of 'Vlan' and 'Vlan'

Today each operator has its own method: __eq__ (==), __ne__ (!=), __lt__ (<), __le__ (<=), __gt__ (>) and __ge__ (>=). They're called rich comparisons. To avoid writing all 6, define __eq__ and one ordering method, and let functools.total_ordering fill in the rest.

from functools import total_ordering


@total_ordering
class Route:
    def __init__(self, prefix, distance):
        self.prefix = prefix
        self.distance = distance

    def __eq__(self, other):
        if not isinstance(other, Route):
            return NotImplemented
        return self.distance == other.distance

    def __lt__(self, other):
        if not isinstance(other, Route):
            return NotImplemented
        return self.distance < other.distance

    def __repr__(self):
        return f"Route({self.prefix!r}, {self.distance})"


ospf = Route("10.1.0.0/16", 110)
static = Route("10.1.0.0/16", 1)
ebgp = Route("10.1.0.0/16", 20)
print(static < ospf, ospf >= ebgp, ebgp == Route("x", 20))
print(sorted([ospf, static, ebgp]))
print(min([ospf, static, ebgp]))
True True True
[Route('10.1.0.0/16', 1), Route('10.1.0.0/16', 20), Route('10.1.0.0/16', 110)]
Route('10.1.0.0/16', 1)

The routes are compared by administrative distance, the way a router chooses between protocols. Returning NotImplemented tells Python you don't know how to compare with that type, and Python decides what to do. sorted() and min() use __lt__ under the hood.

Python 3.14 update. The book describes __cmp__, a single method that returned a negative number, zero or a positive number. Python 3 removed it along with the cmp() function: if you define it, Python ignores it and < raises TypeError. Use rich comparisons with total_ordering, or the key= parameter of sorted(). Along the same lines, __nonzero__ was renamed __bool__.

Dataclasses

Many classes only hold data: an OSPF neighbor, an inventory record, an API response. Writing __init__, __repr__ and __eq__ by hand for each one is repetitive. The @dataclass decorator (Python 3.7, PEP 557) generates them from attributes annotated with their type:

from dataclasses import dataclass, field


@dataclass(order=True)
class Neighbor:
    priority: int
    router_id: str
    interface: str = "Gi0/0"
    routes: list[str] = field(default_factory=list)


a = Neighbor(1, "1.1.1.1")
b = Neighbor(1, "2.2.2.2", "Gi0/1")
print(a)
print(a == Neighbor(1, "1.1.1.1"))
print(sorted([b, a])[0].router_id)
a.routes.append("10.0.0.0/24")
print(a.routes, b.routes)
Neighbor(priority=1, router_id='1.1.1.1', interface='Gi0/0', routes=[])
True
1.1.1.1
['10.0.0.0/24'] []

With order=True it also generates the comparisons, which order field by field. field(default_factory=list) creates a new list for each object: it's the same mutable-default trap you saw with functions, solved out of the box.

Challenge

Answer before you open the solution.

1. Why is __init__(self, hostname) called with a single argument?

Because Python passes self automatically. self is the newly created object. You only provide the other arguments: Router("edge-01").

2. With class C(A, B), if A and B define the same method, which one does C use?

A's. Python searches in MRO order, which starts with the leftmost class. You can check it with C.__mro__.

3. Does self.__password make the attribute inaccessible from outside?

No. Name mangling renames it to _Class__password, which is still accessible. It's meant to avoid name clashes with subclasses, not to protect data.

4. What's the difference between __str__ and __repr__?

Their audience. __str__ produces readable text for people, and print() uses it. __repr__ produces a precise representation for programmers; the interpreter and lists use it, and it's the fallback when there's no __str__.

5. What do you write today instead of __cmp__ so you can sort your objects?

Rich comparisons. Define __eq__ and __lt__, and decorate the class with functools.total_ordering to get the rest. Another option is @dataclass(order=True).

Key takeaways

  • A class is a template; each object has its own state in attributes and its behavior in methods.
  • __init__ initializes the object, and self is the object each method works on.
  • Inheritance reuses code; super() calls the superclass version following the MRO.
  • Python practices duck typing: what matters is which methods an object has, not which class it comes from.
  • _name is an internal-use convention and __name triggers name mangling; neither is truly private.
  • @property controls access to an attribute without changing how it's used.
  • In Python 3 every class inherits from object; __cmp__ no longer exists.
  • @dataclass generates the repetitive methods of data classes.

In the next chapter, you'll revisit objects you already know, like strings, lists and dictionaries, to discover their most useful methods.

Official resources

Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.

Navigate