Methods
Attributes describe an object, and methods allow you to
interact with an object. Methods are functions you define
as part of a class. In the previous section, you created an
object and applied some attributes to it. Example 4-1
shows how you can work with an object by using
methods. A method that allows you to see the details
hidden within an object without typing a bunch of
commands over and over would be a useful method to
add to a class. Building on the previous example,
Example 4-1 adds a new function called getdesc() to
format and print the key attributes of your router. Notice
that you pass self to this function only, as self can
access the attributes applied during initialization.
Example 4-1 Router Class Example
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
def getdesc(self):
'''return a formatted description of
the router'''
desc = f'Router Model :
{self.model}\n'\
f'Software Version :
{self.swversion}\n'\
f'Router Management Address:
{self.ip_add}'
return desc
rtr1 = Router('iosV', '15.6.7', '10.10.10.1')
rtr2 = Router('isr4221', '16.9.5',
'10.10.10.5')
print('Rtr1\n', rtr1.getdesc(), '\n', sep='')
print('Rtr2\n', rtr2.getdesc(), sep='')