DevNet Associate DEVASC 200-901 Official Certification Guide by Adrian Iliesiu (z-lib.org)

(andrew) #1

class a name, and then closing with a colon. Pep8
(introduced in Chapter 3) recommends capitalizing a
class name to differentiate it from a variable. Here is a
simple example of creating a class in Python:


>>> class Router:
pass

This example uses pass as a sort of placeholder that
allows the class to be defined and set up to be used as an
object. To make the class more useful, you can add some
attributes to it. In the case of a router, you typically have
some values that you want to have when you instantiate
the class. Every router has a model name, a software
version, and an IP address for management. You also
need to pass some values to get started. The first value is
always self. The reason for this will become obvious
when you instantiate the class: The self value passes the
object name that you select to instantiate the class. In the
following example, the object you will create is rtr1:


Click here to view code image


class Router:
'''Router Class'''
def __init__(self, model, swversion, ip_add):
'''initialize values'''
self.model = model
self.swversion = swversion
self.ip_add = ip_add

rtr1 = Router('iosV', '15.6.7', '10.10.10.1')

After defining the class, you add a docstring to document
what the class is for and then you create a function that
calls init, which is a special case that is used for
the setup of the class. (In init, the double
underscores are called dunder or magic methods.)
Functions that are within the class are called methods

Free download pdf